MATLAB - 楼层问题
我是 MATLAB 初学者。 问题是:
>> a = floor(7/2.5)
a =
2.00
>> b = rem(7,2.5)
b =
2.00
>> c = floor(b/2)
c =
0
c 应该是 1,对吧? 为什么是0???
直接输入 b = 2 时则不同:
>> b = 2
b =
2.00
>> c = floor(b/2)
c =
1.00
I'm a MATLAB beginner. Here's the problem:
>> a = floor(7/2.5)
a =
2.00
>> b = rem(7,2.5)
b =
2.00
>> c = floor(b/2)
c =
0
c should be 1, right? Why is it 0???
It is different when b = 2 is entered directly as follows:
>> b = 2
b =
2.00
>> c = floor(b/2)
c =
1.00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之:截断错误。
你是对的,精确算术中 c 应该是 1.0。 但是,由于您在 rem 的参数中使用了浮点数,因此您得到的答案是浮点数。 显然,b 不完全是 2,而是 2.0,这意味着它是非常接近 2 的双精度数。因此,b/2 变成双精度数 1.0,显然在这种情况下它的值略小于 1,给你一个 0整数值。 如果您想防止这种情况发生,请同时使用 Floor 和 ceil,并比较这些值。
如果要将答案转换为整数,只需使用舍入而不是下限即可。
In two words: truncation errors.
You're right, c should be 1.0 in exact arithmetic. However, since you used a float in the arguments of rem, you get the answer as a float. Apparently, b is not exactly 2, but 2.0, which means that it is a double very close to 2. Therefore, b/2 becomes the double 1.0, apparently in this case its value is slightly less than one, giving you a 0 as the integer value. If you want to prevent this, use both floor and ceil, and compare the values.
If you want to convert the answer to integer, just use round instead of floor.
如果您将该行添加
到示例中,您将看到结果
,这意味着 Matlab 计算出的 b 值接近但不完全是 2。 这在处理浮点数时经常出现。 尝试
获取更多信息。
If you add the line
to your example you'll see the result
meaning Matlab calculated a number close to, but not exactly, 2 for b. This comes up quite a bit in working with floating point numbers. Try
for more information.
此类数值问题也在 MATLAB 中处理常见问题解答
Numerical issues of this sort are also dealt with in the MATLAB FAQ
是的,这是一个数字问题。 你应该小心使用这些东西。 如果您想要精确的算术,您应该尝试使用“sym”作为您的数字,例如,
那么您将不会出现任何此类错误,但您的计算会慢得多。
Yeah that is a numerical issue. You should use such things with care. If you want exact arithmetic , you should try 'sym' for your number e.g.
Then you will not any such errors, but your computations will be much slower.