Matlab给出了错误的答案 [英] Matlab gives wrong answer
问题描述
如果执行以下代码,则MATLAB会出错.有人可以验证吗?
If the following code is executed MATLAB makes a mistake. Can someone verify this?
floor([0.1:0.1:2]/0.01)
那129在这里做什么?
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
推荐答案
由于冒号生成的向量,这是一个浮点数舍入错误.
就像拉斯曼说的那样,如果您这样做:
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)
没有舍入错误.
但是,基于冒号运算符如何工作,我建议您进行相同的计算,如下所示:
However, based on how the colon operator works, I suggest that you do the same calculation like this:
floor([(1:20)/10] / 0.01)
[ 编辑 :在Rasman评论之后,我将补充说,后一种方法同样适用于负值,而添加eps
有时会失败]
[Edit: following Rasman's comment, I will add that the latter approach works for negative values as well, while adding eps
sometimes fails]
最重要的是,最好使用带有 integer 数字的冒号运算符,以最大程度地减少舍入误差.
The bottom line is that it is better using the colon-operator with integer numbers to minimize rounding errors.
这篇关于Matlab给出了错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!