代码之家  ›  专栏  ›  技术社区  ›  grokus

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

  •  7
  • grokus  · 技术社区  · 15 年前

    我想得到 1/7 精度更高,但被截断了。如何在转换有理数时获得更好的精度?

    >>> str(1.0/7)[:50]
    '0.142857142857'
    
    4 回复  |  直到 10 年前
        1
  •  9
  •   Daniel G    15 年前

    python有一个用于任意精度计算的内置库:decimal。例如:

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

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

        2
  •  6
  •   Jimmy    15 年前

    你可以把分子乘以一个大的10^n,然后用任意精度的整数。

    编辑

    我是说:

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

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

        3
  •  3
  •   Sinan Ünür    15 年前

    使用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" 会给你的 幻觉 更精确。

        4
  •  2
  •   Alex Martelli    15 年前

    gmpy :

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

    你不能用普通的浮点数来实现它——它们的精度不足以容纳50位数字!我想有一种方法可以做到(在2.6或更好的版本中) fractions.Fraction ,但我不熟悉任何格式化它的方法,除了 '1/7' (在你的情况下不是很有用!-)

    推荐文章
    Antoine C.  ·  舍入浮点数
    10 年前