如何消除 Perl 舍入错误 [英] How to eliminate Perl rounding errors

查看:38
本文介绍了如何消除 Perl 舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下程序:

$x=12345678901.234567000;
$y=($x-int($x))*1000000000;
printf("%f:%f\n",$x,$y);

以下是印刷品:

12345678901.234568:234567642.211914

我期待:

12345678901.234567:234567000

这似乎是 Perl 中的某种舍入问题.
我该如何更改它以获取 234567000?
我做错了什么吗?

This appears to be some sort of rounding issue in Perl.
How could I change it to get 234567000 instead?
Did I do something wrong?

推荐答案

Make "use bignum;"程序的第一行.

Make "use bignum;" the first line of your program.

其他答案解释了使用浮点算术时会发生什么 - 最后的一些数字实际上并不是答案的一部分.这是为了使计算能够在合理的时间和空间内完成.如果您愿意使用无限的时间和空间来处理数字,那么您可以使用任意精度的数字和数学,这就是使用 bignum"所实现的.它更慢,占用更多内存,但它的工作原理就像你在小学学到的数学一样.

Other answers explain what to expect when using floating point arithmetic -- that some digits towards the end are not really part of the answer. This is to make the computations do-able in a reasonable amount of time and space. If you are willing to use unbounded time and space to work with numbers, then you can use arbitrary-precision numbers and math, which is what "use bignum" enables. It's slower and uses more memory, but it works like math you learned in elementary school.

一般来说,最好在将程序转换为任意精度数学之前详细了解浮点数学的工作原理.只有在非常奇怪的情况下才需要它.

In general, it's best to learn more about how floating point math works before converting your program to arbitrary-precision math. It's only needed in very strange situations.

这篇关于如何消除 Perl 舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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