python - 如何使用 python 2.7 计算 pi 到 1000 位?
问题描述
我想在 python 2 中将 pi 计算为一个大数字,但代码不起作用 - 它只是关闭,我想看看需要多长时间。
from decimal import Decimal, getcontext
from time import time, strftime
import datetime
def arccot(x, digits):
getcontext().prec = digits
total = 0
n = 1
while Decimal((2 * n - 1) * x ** (2 * n - 1)) < Decimal(10 ** digits):
term = ((-1)**(n - 1)) * 1 / Decimal((2 * n - 1) * x ** (2 * n - 1))
total += term
n += 1
return total
def pi(decimals):
timestart = time()
print "pi = " + str(Decimal(4 * (4 * arccot(5, decimals + 3) - arccot(239,
decimals + 3))).quantize(Decimal(10) ** (-decimals)))
timeelapsedint = round(time() - timestart, 2)
timeelapsedstr = str(datetime.timedelta(seconds = round(
timeelapsedint, 0)))
print "runtime: " + timeelapsedstr + " or " + str(
timeelapsedint) + " seconds."
解决方案
只需调用您的函数(注意最后一行):
# Pi Calculator
# Python 2.7.3
# After running, type "pi(n)" where n is the number of decimals for pi. For
# example, if you would like to calculate 100 decimals for pi, type "pi(100)".
# import python libraries
from decimal import Decimal, getcontext
from time import time, strftime
import datetime
# arccot function using power formula arccot = 1/x - 1/(3x^3) + 1/(5x^5) ...
def arccot(x, digits):
# set precision and starting values
getcontext().prec = digits
total = 0
n = 1
# loop while new term is large enough to actually change the total
while Decimal((2 * n - 1) * x ** (2 * n - 1)) < Decimal(10 ** digits):
# find value of new term
term = ((-1)**(n - 1)) * 1 / Decimal((2 * n - 1) * x ** (2 * n - 1))
# add the new term to the total
total += term
# next n
n += 1
# return the sum
return total
# pi function
def pi(decimals):
# start timer
timestart = time()
# find pi using Machin's Formula pi = 4 * (4 * arccot(5) - arccot(239))
# and the power formula for arccot (see arccot function above)
print "pi = " + str(Decimal(4 * (4 * arccot(5, decimals + 3) - arccot(239, decimals + 3))).quantize(Decimal(10) ** (-decimals)))
# display elapsed time
timeelapsedint = round(time() - timestart, 2)
timeelapsedstr = str(datetime.timedelta(seconds = round(timeelapsedint, 0)))
print "runtime: " + timeelapsedstr + " or " + str(timeelapsedint) + " seconds."
pi(1000)
输出:
pi = 3.14159265358979323....more digits
runtime: 0:00:00 or 0.22 seconds.
此外,您的代码格式不正确,但我无法编辑它。我的代码段格式正确。
推荐阅读
- java - Jsoup获取href的内容
- assembly - x86 汇编 - 错误 A2022:指令操作数必须相同大小
- azure-data-factory - 更改数据类型 - Azure 数据工厂的数据流
- c - 如何在 C 中实现 futimens 函数以更改文件上的时间戳
- spring - 使用 r2dbc 设置集成测试
- python - 基于字符串数据类型的预测
- javascript - 如何在这个(非常低效的)代码中修复穿墙故障
- sql-server - 使用 SSMS 时 SQL 还原失败并出现错误
- c - 如何使用指针算法指向链表结构的下一个元素?
- javascript - React-redux - 嵌套连接组件