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

3 views (last 30 days)
Abdolkarim Behravan on 16 Dec 2021
Commented: Image Analyst on 17 Dec 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.

John D'Errico on 16 Dec 2021
Edited: John D'Errico on 16 Dec 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 CommentsShowHide 1 older comment
Image Analyst on 17 Dec 2021
Like, for example
index = round(0.14*100);
x(index) = 5;

Star Strider on 16 Dec 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.
.
##### 2 CommentsShowHide 1 older comment
Star Strider on 16 Dec 2021
My pleasure!
.

Image Analyst on 16 Dec 2021
Abdolkarim Behravan on 16 Dec 2021
Tnx, I got it.

R2021b

### Community Treasure Hunt

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

Start Hunting!