![](/img/trans.png)
[英]how do i display the label that more than 50% accuracy in line chart using python?
[英]How do I get Python to display more than 50 decimal places?
我已經寫了這個程序來計算圓周率。 它給我50個小數位。 如何獲得更高的精度?
# 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))
您必須將Decimal prec設置為更高的值。 請參閱此示例線程 。 官方python網站上有更多示例。
另外,您應該使用十進制進行所有計算,而不僅僅是最后一步。 否則,您將無法獲得所需的精度。
或者看一下mpmath,它支持任意精度的浮點數。
並且,有些算法會無限期地一次生成pi的一位(無需極高的精度要求)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.