使用简单算术的Ruby数字精度 [英] Ruby number precision with simple arithmetic

查看:72
本文介绍了使用简单算术的Ruby数字精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Ruby,这很有趣,也可以用来创建网站(但这无关紧要).在玩游戏时,我注意到怪异"

I'm learning Ruby for fun, and for creating websites also (but that's irrelevant). While playing with it, i noticed something "weird"

当我用irb计算4.21 + 5时,它回答9.21(很奇怪,对吧?)

When I compute 4.21 + 5 with irb, it answers 9.21 (weird, right?)

当我计算4.23 + 5时,得出的数值为9.23(哇,那肯定很奇怪).

when I compute 4.23 + 5, it gives 9.23 (waw, that's definitely weird).

当我键入4.22 + 5时,它将回答9.21999 ...(w ...等等!那真是太奇怪了).

and when i type 4.22 + 5, it answers 9.21999... (w...wait! that's really weird).

因此,我的问题是:怎么回事? 我会用除法或很大的数字来理解这种行为,但是在这种简单情况下.... ???

Hence my question: what's going on? I'd understand this behavior with division or really big numbers, but in this simple case....???

这是否意味着我无法使用Ruby开发会计应用程序? 是否有补丁或要应用的东西? (很可能是我的大脑)

Does it mean that i can't develop an accounting app with Ruby? Is there a patch or something to be applied? (to my brains, most likely)

推荐答案

您应该阅读计算机中的浮点表示形式. 本指南是一个很好的起点.这是它的简称:

You should read up on floating point representation in computers. This guide is a good place to start. Here's the short of it:

由于在内部,计算机使用 格式(二进制浮点数) 无法准确表示一个数字 像是0.1、0.2或0.3.

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

编译代码或 解释,您的"0.1"已经 四舍五入到最接近的数字 格式,这会导致 舍入误差甚至在 计算发生.

When the code is compiled or interpreted, your "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

顺便说一句,我不确定为什么您认为4.21 + 5 = 9.21或4.23 + 5 = 9.23很奇怪.如果您认为这很奇怪,因为一个文字是整数而一个是浮点数(最终以浮点数响应),这就是Ruby和其他一些语言处理数字类型差异的方式.如果Ruby降低了float的精度并只给了整数9(9),那么任何整数常量都将有效地更改为float.

By the way, I'm not sure why you think 4.21 + 5 = 9.21 or 4.23 + 5 = 9.23 is weird. If you think it's weird because one literal is an integer and one is a float, which ends up as a float response, that's how Ruby and some other languages handle differences in number types. It wouldn't be handy if Ruby dropped your float's precision and gave you just an integer back (9), so any integer literals are effectively changed to floats.

关于在金融应用程序中使用浮点数,请查看开发金融应用程序.主要要点是使用Decimal对象与Float.

As for using floating-point numbers in a financial application, check out Developing financial application. The main takeaway is use the Decimal object vs. Float.

这篇关于使用简单算术的Ruby数字精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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