I've compiled the code below and i don't know why it doesn't give exact zero.
I'll appreciate if someone helps me.
format long
x=5.4;
y=x-5;
z=y-0.4;
disp(z)
Best Answer
"..i don't know why it doesn't give exact zero."
The decimal values 5.4 and 0.4 cannot be represented exactly using binary floating point numbers, in just the same way that you cannot write 1/3 using a finite decimal fraction.
Use num2strexact see the precise decimal values of the closest floating point binary numbers:
The behaviors of floating point numbers are quite well documented, you need to learn how to write your code taking them into account. Start by reading these:
The values that you are trying to compare cannot be exactly represented using binary floating point numbers. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact values 0.1 or 0.001. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.1 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
To compare floating point values always compare the absolute difference against a tolerance:
abs(A-B)<tol
You need to learn about the limits of floating point numbers. Start by reading these:
Not bizarre at all, you just need to learn about how floating point numbers work.
"I change 0.02 to 0.03"
Actually you don't, because neither of those values can be exactly represented using binary floating point numbers. What you see printed in the command window is the closestrepresentation to 5 or 16 significant digits, depending on your currentformat setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa'snum2strexact and you will see thatnone of those values really have the exact value0.02 or0.03. All you are looking at is arepresentation of those floating point numbers displayed in the command window, to the precision defined by yourformat setting. Just because you see0.02 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value isdisplayed by changing theformat.
You need to learn about the limits of floating point numbers. Start by reading these:
Best Answer