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

2 Ansichten (letzte 30 Tage)
Richard Brown
Richard Brown am 18 Jan. 2021
Kommentiert: Richard Brown am 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

Akzeptierte Antwort

Stephen23
Stephen23 am 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 Kommentare
Jan
Jan am 18 Jan. 2021
@Richard Brown: Welcome to the world of numerics with limited precision.
Richard Brown
Richard Brown am 19 Jan. 2021
Thank you so much Stephen! Thank you so much Jan! For your great answers and willingness to share your knowledge :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by