MATLAB Answers

The for loop gives an odd number instead of 0?

1 view (last 30 days)
sama on 9 Nov 2015
Commented: sama on 16 Nov 2015
Hello, I have a easy question but it is making me crazy.I have a for loop as follow:
for LL=1:DD
When I see the result, Zr4 is changing from 1 to 1.3878e-16. I am so confused. after 0.1 instead of giving 0, it gives 1.3878e-16. I appreciate if you help me. Thanks


Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 9 Nov 2015
Edited: Stephen Cobeldick on 10 Nov 2015
Floating point numbers are how decimal values are stored in your computer: they do not have infinite precision, and they can only approximate many values. Even if it looks like the "actual" value is being shown to you this does not mean that the internal representation inside your computer is the same value.
Lets have a quick look at those values:
>> zr4=1.1;
>> zr2=-0.1;
>> fprintf('%.30f\n',zr4)
>> fprintf('%.30f\n',zr2)
Do you see that the trailing digits are not all zero. This means it is not possible to store them exactly using the binary numbers that computers use (unless you have infinite binary digits stored in infinite memory). This is not a problem with MATLAB, this is simply how all (binary) computers store numbers.
Of course this means that every operation you perform on floating point values will accumulate these errors. It is up to you (and every other programmer) to design programs that take this "floating point error" into account.
Read all about it:
And if you want to see what the decimal equivalent of a floating point value is, then try this FEX submission:
As its author points out: "Don't confuse the exact conversion with significance!"

  1 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.