colon operator rounding problem
Show older comments
Hello everyone!
I encountered a problem in one of my code, using the semi colon operator like this:
a = 0:0.1:120;
will not give me exactly what I want, it does return 0, 0.1, 0.2 etc, but with a small imprecision (equal to eps actually)
the following code :
a = 0:0.1:120;
disp(a(20));
disp(a(20)-1.9)
isequal(a(20),1.9)
is returning:
1.9
2.22044604925031e-16
ans =
0
Any help ? I really need this isequal(a(20),1.9) to return 1...
thanks !
2 Comments
Ambroise
on 10 Jul 2015
The problem is the real value of 0.1...
If you really want to see what the floating point values really are, try this:
Accepted Answer
More Answers (2)
Use
a = linspace(0, 120, 1201);
But in general don't use
a(20) == 1.9
but
abs(a(20) - 1.9) <= eps
If you don't want to do it this way, just define
a(20) = 1.9;
Steven Lord
on 10 Jul 2015
0 votes
See question 1 in the Mathematics section of the FAQ for a more detailed explanation of this behavior.
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!