Matlab gives wrong answer

匆匆过客 提交于 2019-11-26 22:03:15

问题


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??

ans = 10 20 30 40 50 60 70 80 90 100 110 120 129 140 150 160 170 180 190 200

回答1:


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.




回答2:


It is probably doing a floating point calculation resulting in an inexact value of 129.99999999999999... something instead of 130. and then you floor it to 129.




回答3:


it's a rounding approximation brought on by the 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))


来源:https://stackoverflow.com/questions/10930750/matlab-gives-wrong-answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!