在Ruby中,为什么“100.7”.to_f.modulo(1) = 0.700000000000003?
这对我来说很奇怪:
irb(main):012:0> "100.7".to_f.modulo(1)
=> 0.700000000000003
为什么最后是3?
irb(main):019:0> "10.7".to_f.modulo(1)
=> 0.699999999999999
同样的事情......我们只是得到这个值除以一的余数。 应该是准确的。
This is very strange to me:
irb(main):012:0> "100.7".to_f.modulo(1)
=> 0.700000000000003
Why the 3 at the end?
irb(main):019:0> "10.7".to_f.modulo(1)
=> 0.699999999999999
Same thing here...we are only getting the remainder of this value divided by one. It should be exact.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
欢迎来到浮点数学。 有许多数字无法用标准浮点表示法表示,并且结果略有偏差。
这很容易说明如下:
结果是:
请注意,数字越大,小数点后的精度就越低。 这是因为有固定的精度可用于表示整个数字。
Welcome to floating point math. There are many numbers which cannot be represented in standard floating point notation and come out just a tiny bit off.
This is easily illustrated as follows:
Where the result is:
Notice that the larger the number gets, the lower the precision beyond the decimal place. This is because there is a fixed amount of precision available to represent the entire number.
这是典型的浮点舍入。 您根本无法用 Float 中的固定位数表示每个十进制数,因此某些值会四舍五入到可以表示的最接近的值。
因此,建议您不要比较 Floats 是否相等。 比较小于或大于,但决不完全相等。
http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding
简单来说,并不是“应该准确”的情况。 不要指望浮点小数会出现这种情况。
This is typical floating point rounding. You simply cannot express every single decimal number in the fixed number of bits in a Float, so some values are rounded to the nearest value that can be represented.
Due to this, it is suggested that you don't compare Floats for equality. Compare for less than or greater than, but never exact equality.
http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding
Simply, it is not the case that "it should be exact". Don't expect that from floating point decimals.
每个计算机科学家应该了解的浮点运算知识
What Every Computer Scientist Should Know About Floating-Point Arithmetic
这是因为不可能精确地表示所有浮点数。
this is because it's not possible to represent all floating point numbers exactly.
浮点数并不精确。 简而言之,不可能在有限数量的位中存储无限数量的值。
较长的版本是每个计算机科学家应该了解的浮点运算
Floating points are not exact. The short version is it's not possible to store an infinite amount of values in a finite amount of bits.
The longer version is What Every Computer Scientist Should Know About Floating-Point Arithmetic