how to round a rational number based on a given difference range
1 view (last 30 days)
Show older comments
Hi,
I am taking two inputs from a user, VCR and x_diff. VCR can be integer or decimal, I used format rat to change it to Num/Den format. Then, this will be used later for other codes. My issue now, I want to round these Num and Den values based on a given acceptable difference range (x_diff), so for example VCR=0.76 and x_diff=0.02 would result in assiging VCR=0.75 which is 3/4 instead of 19/25 (0.76) The minimum Num and Den values the better for my problem. Another example, VCR=0.1 and using x_diff=0.1, the assigned new VCR is 0.2 which is 1/5 instead of 1/10 previously.
I have developed the code as following:
function [VCR_new]= Rat_test(VCR, x_diff)
% VCR= Gain, x_diff is acceptable difference
F=[1 1 2 3 5 8 13 21 34 55 89 144]; % Fibonnacci series
format rat % change VCR to rational VCR=Num/Den
for m=1:size(VCR,2);
[Num(m), Den(m)] = numden(sym(VCR(m))); % Num of simplest form of VCR
i=1; j=1; % initialization
if x_diff~= 0
while F(i)< Den(m) % to make sure assigned new number does not exceeding the Den(m)
Den_new = i;
for j=1: Den(m)
VCRx_New = j/i;
if abs(VCRx_New- Num(m)/Den(m)) <= x_diff
Num(m)= j; Den(m)=i;
x_diff = 0;
else
end
end
i=i+1;
end
else
end
VCR_new (m)= Num(m)/Den(m);
end
My concern: Is there any way to minimize/optimize this code?
Thanks
0 Comments
Answers (0)
See Also
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!