简体   繁体   English

如何让Python显示超过50个小数位?

[英]How do I get Python to display more than 50 decimal places?

I have written this program to calculate pi. 我已经写了这个程序来计算圆周率。 It gives me 50 decimal places. 它给我50个小数位。 How can I get more precision? 如何获得更高的精度?

# pi.py - arctan(1) * 4 = pi
from math import *
from decimal import *

err = 0.0000000000000001

def arctan(n, err):
    """Uses Gregory's formula for calculating atan."""
    temp = n
    atan = 0
    i = 3
    while (abs(atan - n) > err):
        atan = n
        n = n - (pow(temp, i)/i) + ((pow(temp, i + 2)) / (i + 2))
        i += 4
    return n

def euler(a, b, err):
    """Uses Euler's formula and fibonacci numbers."""
    euler = 0
    temp = 5
    while (abs(temp - euler) > err):
        temp = euler
        euler += arctan(1/b, err)
        a = b + a
        b = b + a
    return euler


pi = euler(1, 2, err) * 4
print(Decimal.from_float(pi))

You must set the Decimal prec to a higher value. 您必须将Decimal prec设置为更高的值。 See this example thread . 请参阅此示例线程 The official python site has a lot more examples. 官方python网站上有更多示例。

Also, you should make all your calculations using decimal, not just the last step. 另外,您应该使用十进制进行所有计算,而不仅仅是最后一步。 Otherwise you will not get the precision you need. 否则,您将无法获得所需的精度。

Or look at mpmath, which supports arbitrary precision floats. 或者看一下mpmath,它支持任意精度的浮点数。

And, there are algorithms which will generate one digit of pi at a time, indefinitely (without exceedingly high precision requirements). 并且,有些算法会无限期地一次生成pi的一位(无需极高的精度要求)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM