"If function" can't distinguish i ~= 1.6.
2 views (last 30 days)
Show older comments
Richard Brown
on 18 Jan 2021
Commented: Richard Brown
on 19 Jan 2021
I was trying to plot a series of figures and use "if elseif else" function to do this job. But I found out "if i ~= 1.6" cannot be distinguished. I wrote a simple code here. When "i=1.6","a=1.6". This weird thing only happens when i=1.6.
Could someone help me with it? Is it a bug or is there something wrong with my code.
Thank you very much!
a=0;
for i = 1.4:0.1:1.9
if i ~= 1.6
a = i;
end
end
0 Comments
Accepted Answer
Stephen23
on 18 Jan 2021
"This weird thing only happens when i=1.6."
Nothing weird happens: you generate binary floating point numbers using two different methods and get slightly different output values for some input values. That is in the nature of binary floating point numbers.
"Is it a bug..."
No.
"...or is there something wrong with my code."
Yes. You assumed that numeric mathematics is the same as symbolic or algebraic mathematics. But it isn't.
In your example you did not take into account the acccumulated floating point error, which means that you should never test for exact equality of binary floating point numbers, but should always compare the absolute difference againsts a tolerance:
abs(A-B)<tol
Or change the algorithm to work with integer values only.
Read more about binary floating point numbers:
This is worth reading as well:
3 Comments
More Answers (0)
See Also
Categories
Find more on Graphics Object Programming 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!