Ruby 数学运算的精度问题

发布于 2024-09-25 05:46:21 字数 399 浏览 1 评论 0原文

您知道如何以数学精度解决以下问题吗?

p RUBY_VERSION # => "1.9.1"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.1
p 90.0%1 # => 0.0
p 90.1%1 # => 0.0999999999999943
p 900.1%1 # => 0.100000000000023

p RUBY_VERSION # => "1.9.2"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.10000000000000009
p 90.0%1 # => 0.0
p 90.1%1 # => 0.09999999999999432
p 900.1%1 # => 0.10000000000002274

Do you know how to fix the following issue with math precision?

p RUBY_VERSION # => "1.9.1"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.1
p 90.0%1 # => 0.0
p 90.1%1 # => 0.0999999999999943
p 900.1%1 # => 0.100000000000023

p RUBY_VERSION # => "1.9.2"
p 0.1%1 # => 0.1
p 1.1%1 # => 0.10000000000000009
p 90.0%1 # => 0.0
p 90.1%1 # => 0.09999999999999432
p 900.1%1 # => 0.10000000000002274

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萤火眠眠 2024-10-02 05:46:21

大十进制

正如所说;

将无限多个实数压缩为有限数量的位数需要近似表示。

然而,我使用 BigDecimal 类。引用它的简介

Ruby 提供对任意精度整数算术的内置支持。例如:

42**13 -> 1265437718438866624512

BigDecimal 为非常大或非常精确的浮点数提供类似的支持。

举一个例子;

>> x = BigDecimal.new('900.1')
=> #<BigDecimal:101113be8,'0.9001E3',8(8)>
>> x % 1
=> #<BigDecimal:10110b498,'0.1E0',4(16)>
>> y = x % 1
=> #<BigDecimal:101104760,'0.1E0',4(16)>
>> y.to_s
=> "0.1E0"
>> y.to_f
=> 0.1

正如您所看到的,确保良好的精度是可能的,但需要付出一些努力。

Big Decimal

As the man said;

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation.

I have however had great success using the BigDecimal class. To quote its intro

Ruby provides built-in support for arbitrary precision integer arithmetic. For example:

42**13 -> 1265437718438866624512

BigDecimal provides similar support for very large or very accurate floating point numbers.

Taking one of your examples;

>> x = BigDecimal.new('900.1')
=> #<BigDecimal:101113be8,'0.9001E3',8(8)>
>> x % 1
=> #<BigDecimal:10110b498,'0.1E0',4(16)>
>> y = x % 1
=> #<BigDecimal:101104760,'0.1E0',4(16)>
>> y.to_s
=> "0.1E0"
>> y.to_f
=> 0.1

As you can see, ensuring decent precision is possible but it requires a little bit of effort.

旧城空念 2024-10-02 05:46:21

所有计算机语言都是如此,而不仅仅是 Ruby。这是在二进制计算机上表示浮点数的功能:

每个计算机科学家应该知道的内容关于浮点运算

This is true of all computer languages, not just Ruby. It's a feature of representing floating point numbers on binary computers:

What Every Computer Scientist Should Know About Floating Point Arithmetic

梦萦几度 2024-10-02 05:46:21

0.1 写入浮点总是会导致舍入错误。如果您想要“精确”的十进制表示形式,则应使用 Decimal 类型

Writing 0.1 into a floating point will always result in rounding errors. If you want 'precise' decimal representation, you should use the Decimal type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文