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

gro*_*kus 7 python floating-point floating-point-precision

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

>>> str(1.0/7)[:50]
'0.142857142857'
Run Code Online (Sandbox Code Playgroud)

Dan*_*l G 9

Python有一个用于任意精度计算的内置库:Decimal.例如:

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

有关更多详细信息,请查看Python Decimal文档.您可以将精度更改为您需要的最高精度.


Jim*_*mmy 6

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

编辑

我的意思是:

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

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