Matlab gives the wrong answer

If the following code is executed, MATLAB makes an error. Can anyone confirm this?

floor([0.1:0.1:2]/0.01) 

So what are 129 doing here?

 ans = 10 20 30 40 50 60 70 80 90 100 110 120 129 140 150 160 170 180 190 200 
+6
source share
3 answers

This is a floating point rounding error due to the colon-generated vector.
As Rasman said, if you do this:

 floor((0.1:0.1:2 + eps) / 0.01) 

No rounding errors.

However, based on how the colon operator works , I suggest doing the same calculation as follows:

 floor([(1:20)/10] / 0.01) 

[ Edit : after Rasman's comment, I’ll add that the latter approach also works for negative values, and sometimes eps added)

The bottom line is that it’s best to use a colon operator with integers to minimize rounding errors.

+9
source

Probably this floating point calculation leads to an inaccurate value of 129.99999999999999 ... something instead of 130. and then you make it to 129.

+4
source

this is a rounded approximation caused by array construction. The solution would be to add eps:

 floor([0.1:0.1:2]/0.01+ eps([0.1:0.1:2]/0.01)) 
+4
source

Source: https://habr.com/ru/post/917515/


All Articles