MATLAB Answers

"If function" can't distinguish i ~= 1.6.

23 views (last 30 days)
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

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick 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

Stephen Cobeldick
Stephen Cobeldick on 18 Jan 2021
The values are clearly not the same:
V = 1.4:0.1:1.9;
V(3) - 1.6
ans = -2.2204e-16
Jan
Jan on 18 Jan 2021
@Richard Brown: Welcome to the world of numerics with limited precision.
Richard Brown
Richard Brown on 19 Jan 2021
Thank you so much Stephen! Thank you so much Jan! For your great answers and willingness to share your knowledge :)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!