红宝石:在Ruby中从float转换为整数会产生奇怪的结果 [英] ruby: converting from float to integer in ruby produces strange results

查看:71
本文介绍了红宝石:在Ruby中从float转换为整数会产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ree-1.8.7-2010.02 :003 > (10015.8*100.0).to_i
 => 1001579 
ree-1.8.7-2010.02 :004 > 10015.8*100.0
 => 1001580.0 
ree-1.8.7-2010.02 :005 > 1001580.0.to_i
 => 1001580 

红宝石1.8.7产生相同的结果. 有人知道如何消除这种异端吗? =)

ruby 1.8.7 produces the same. Does anybody knows how to eradicate this heresy? =)

推荐答案

实际上,所有这些都是有道理的.

Actually, all of this make sense.

因为对于各种 x 0.8 不能完全由任意系列的 1 / 2 ** x 表示,它必须大致表示,并且恰好小于 10015.8.

Because 0.8 cannot be represented exactly by any series of 1 / 2 ** x for various x, it must be represented approximately, and it happens that this is slightly less than 10015.8.

因此,当您只打印它时,它会进行合理的四舍五入.

So, when you just print it, it is rounded reasonably.

当您将其转换为整数而不添加 0.5 时,它会将 .79999999 ... 截断为 .7

When you convert it to an integer without adding 0.5, it truncates .79999999... to .7

当您键入 10001580.0 时,它具有所有格式的 exact 表示形式,包括浮点和双精度.因此,您不会看到值的截断比下一个整数步骤要小得多.

When you type in 10001580.0, well, that has an exact representation in all formats, including float and double. So you don't see the truncation of a value ever so slightly less than the next integral step.

浮点数并不准确,只是对表示的内容有限制.是的,FP是完全准确的,但不一定代表我们可以轻松使用基数 10 键入的每个数字.(更新/说明:很好,具有讽刺意味的是,它可以精确地表示每个整数,因为每个整数都有 2 ** x 组成,但是每个分数"则是另外一回事. 1/2**x 系列.)

Floating point is not inaccurate, it just has limitations on what can be represented. Yes, FP is perfectly accurate but cannot necessarily represent every number we can easily type in using base 10. (Update/clarification: well, ironically, it can represent exactly every integer, because every integer has a 2 ** x composition, but "every fraction" is another story. Only certain decimal fractions can be exactly composed using a 1/2**x series.)

实际上,JavaScript实现对所有数值使用浮点存储和算术.这是因为FP硬件会为整数生成精确的结果,因此这使JS专家使用(当时)几乎整个32位计算机上的现有硬件进行了52位数学运算.

In fact, JavaScript implementations use floating point storage and arithmetic for all numeric values. This is because FP hardware produces exact results for integers, so this got the JS guys 52-bit math using existing hardware on (at the time) almost-entirely 32-bit machines.

这篇关于红宝石:在Ruby中从float转换为整数会产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆