Matlab gives wrong answer

前端 未结 3 493
小蘑菇
小蘑菇 2020-12-07 02:11

If the following code is executed MATLAB makes a mistake. Can someone verify this?

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

So what is the 129 doing here??<

3条回答
  •  忘掉有多难
    2020-12-07 02:52

    It is a floating point rounding error because of the colon-generated vector.
    Like Rasman said, if you do:

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

    There will be no rounding errors.

    However, based on how the colon operator works, I suggest that you do the same calculation like this:

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

    [Edit: following Rasman's comment, I will add that the latter approach works for negative values as well, while adding eps sometimes fails]

    The bottom line is that it is better using the colon-operator with integer numbers to minimize rounding errors.

提交回复
热议问题