Why does MATLAB give an error with this instruction? x(0.14*100)=5;

3 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

John D'Errico
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
ans = 0
0.14*100 - 14
ans = 1.7764e-15
0.15*100 - 15
ans = 0
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
Abdolkarim Behravan
Abdolkarim Behravan el 16 de Dic. de 2021
I got it, tnx.
I enhanced my program to ignore this tiny bit difference.
Image Analyst
Image Analyst el 17 de Dic. de 2021
Like, for example
index = round(0.14*100);
x(index) = 5;

Iniciar sesión para comentar.

Más respuestas (2)

Star Strider
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.
See the documentation section on Floating-Point Numbers for a detailed discussion.
.

Image Analyst
Image Analyst el 16 de Dic. de 2021

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by