Euler#26,如何将有理数转换为精度更高的字符串?

时间:2009-11-12 03:54:11

标签: python floating-point floating-point-precision

我希望1/7具有更好的精度,但它被截断了。当我转换有理数时,如何才能获得更好的精度?

>>> str(1.0/7)[:50]
'0.142857142857'

4 个答案:

答案 0 :(得分:9)

Python有一个用于任意精度计算的内置库:十进制。例如:

>>>from decimal import Decimal, getcontext
>>>getcontext().prec = 50
>>>x = Decimal(1)/Decimal(7)
>>>x
Decimal('0.14285714285714285714285714285714285714285714285714')
>>>str(x)
'0.14285714285714285714285714285714285714285714285714'

查看Python Decimal documentation了解更多详情。您可以根据需要更改精度。

答案 1 :(得分:6)

你可以将分子乘以一个大的10 ^ N并坚持使用任意精度的整数。

修改

我的意思是:

> def digits(a,b,n=50): return a*10**n/b
.
> digits(1,7)
14285714285714285714285714285714285714285714285714L

Python的整数是任意精度。 Python的浮点数永远不会是任意精度。 (你必须使用Decimal,正如另一个答案所指出的那样)

答案 2 :(得分:3)

使用Perl(因为我不能编写Python; - ):

use strict; use warnings;

use integer;

my $x = 1;
my $y = 7;

for (1 .. 50) {
    $x *= 10 if $x < $y;
    my $q = $x / $y;
    $x -= $q * $y;
    print $q;
}

print "\n";
14285714285714285714285714285714285714285714285714

您可以手动验证,数字重复。使用"%.50f"进行打印将为您提供更精确的幻觉

答案 3 :(得分:2)

使用gmpy

>>> import gmpy
>>> thefraction = gmpy.mpq(1, 7)
>>> hiprecfloat = gmpy.mpf(thefraction, 256)
>>> hiprecfloat.digits(10, 50, -10, 10)
'0.14285714285714285714285714285714285714285714285714'
>>> 

你不能用正常浮动来做 - 它们只有50位数的精度不够!我想有一种方法可以用fractions.Fraction来做(2.6或更好),但我不熟悉任何格式化它而不是'1/7'(在你的情况下不是很有用!) )。

相关问题