Why does MATLAB give an error with this instruction? x(0.14*100)=5;
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Abdolkarim Behravan
el 16 de Dic. de 2021
Comentada: Image Analyst
el 17 de Dic. de 2021
Why I get this error? Is there a Bug in MATLAB?! (Version R2021b)
x(0.12*100)=5; has no error.
x(0.14*100)=5; has an error: "Array indices must be positive integers or logical values".
x(0.15*100)=5; has no error.
0 comentarios
Respuesta aceptada
John D'Errico
el 16 de Dic. de 2021
Editada: John D'Errico
el 16 de Dic. de 2021
Is there a bug in MATLAB? Sigh. If I had a nickel for every time someone has asked that question, I would be wealthy. (It does not matter which release of MATLAB you are using. This would have failed in release 1 also.)
No. There is no bug. What you need to understand is that most decimal numbers are not exactly representable using binary. Don't believe me? What is the exact decimal representation of 2/3 in a finite number of decimal digits? Of course there is none. So then what is the EXACT representatrion of the numbers 0.12, 0.14, and 0.15 in binary form?
0.12 (decimal) = 0.00011110101110000101000111101011100001010001111010111000... (binary)
So an infinitely repeating string of binary bits. There is no finite representation of that number in binary. Likewise...
0.14 (decimal) = 0.0010001111010111000010100011110101110000101000111101100... (binary)
0.15 (decimal) = 0.0010011001100110011001100110011001100110011001100110011... (binary)
In all three cases, these numbers were not exactly represented when you typed 0.12, 0.14, and 0.15. MATLAB represents them as the closest approximation it can find using 52 binary bits of precision.
Now, what happens when you multiplied by 100? Well SOME of the time, you get lucky.
0.12*100 - 12
0.14*100 - 14
0.15*100 - 15
So in two of those cases, the result was indeed exactly an integer. But not in all three cases. The second one failed, because 0.14*100 is not exactly an integer. (READ THE ERROR MESSAGE!)
As you can see, 0.14*100 is just a tiny bit larger than 14, with an error in the least significant bit.
2 comentarios
Image Analyst
el 17 de Dic. de 2021
Like, for example
index = round(0.14*100);
x(index) = 5;
Más respuestas (2)
Star Strider
el 16 de Dic. de 2021
There was a detailed discussion on a closely-related topic recently in Why doesn't 'find' function work properly? The problem is floating-point approximation error.
.
2 comentarios
Ver también
Categorías
Más información sobre Get Started with MATLAB 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!