Question

Just having some issues with variable precision in matlab..

I have the code:

x = 0.1;
syms y;
S = solve(x+1==(1+y)/(1-y),y);
y = double(S);
val = abs(((2^2)*(y^2))/(2*(y-1)^2))

But val is always rounded off. I should be getting val = 0.0049999 but instead I am getting val = 0.0050.

Anyone have any idea why?

Thanks.

EDIT: Adding extra code

x = 0.1;
syms y;
S = solve(x+1==(1+y)/(1-y),y);
y = double(S);
val = abs(((2^2)*(y^2))/(2*(y-1)^2))
sprintf('%22.20f',val)

for i=1:2
    val= val+((2^i)*(y^i))/(i*(y-1)^i);
    sprintf('%22.20f',val)
end

The first sprintf works and shows correct rounding, however the second doesnt!!

Was it helpful?

Solution

It has to do with the floating-point representation and how Matlab displays such numbers for readability. If you add this line to the end of your code:

sprintf('%22.20f',val)

you'll get:

ans =

0.00499999999999999924

Edit
Even though it technically deals with Python, this website offers a brief and concise overview on the limitations of floating-point representations.

OTHER TIPS

Is it possible that you merely set your preferences for displaying numbers to short rather than long? It would help if you eliminated that as a possibility.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top