My loop can't (sometimes...) evaluate its variable
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Floriane A
el 25 de Mzo. de 2021
Comentada: Floriane A
el 25 de Mzo. de 2021
Hello,
I have a problem with a program : It was working yesterday, but this morning it didn't anymore... The same problem also happens with a very basic code :
F=0.32;
for x=-0.5:0.01:0.5
if x==F
disp(x)
end
end
For F=0.32 it doesn't disp the value (even if i write 'x" instead of "disp(x)" etc). For F=0.28, it does work... Not for F=0.29.
I'm a bit lost, did I use something wrong ?
Thank you for your help !
0 comentarios
Respuesta aceptada
Stephen23
el 25 de Mzo. de 2021
Editada: Stephen23
el 25 de Mzo. de 2021
"did I use something wrong ? "
You are testing for exact equality of binary floating point numbers, which is unlikely to be reliable.
The robust approach is to compare the absolute difference against a tolerance:
tol = 1e-10;
..
if abs(x-F)<tol
Read more about binary floating numbers:
This is worth reading as well:
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!