"If function" can't distinguish i ~= 1.6.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Richard Brown
el 18 de En. de 2021
Comentada: Richard Brown
el 19 de En. de 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 comentarios
Respuesta aceptada
Stephen23
el 18 de En. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!