您的解决方案似乎循环了错误的内容:
for number_of_places in fraser:
对于9个位置,这将变成类似以下内容:
for "9" in "3.141592653589793":
这个循环会循环三次,每次都会找到字符串中的一个"9"。我们可以修复你的代码:
from math import pi
fraser = str(pi)
length_of_pi = []
number_of_places = int(raw_input("Enter the number of decimal places you want: "))
for places in range(number_of_places + 1):
length_of_pi.append(str(fraser[places]))
print "".join(length_of_pi)
但是这仍然限制了n
小于len(str(math.pi))
,在Python 2中小于15。对于一个严肃的n
,它会崩溃:
> python test.py
Enter the number of decimal places you want to see: 100
Traceback (most recent call last):
File "test.py", line 10, in <module>
length_of_pi.append(str(fraser[places]))
IndexError: string index out of range
>
要做得更好,我们必须自己计算PI——使用级数评估是一种方法:
from decimal import Decimal, getcontext
TERMS = [(12, 18), (8, 57), (-5, 239)]
def arctan(talj, kvot):
"""Compute arctangent using a series approximation"""
summation = 0
talj *= product
qfactor = 1
while talj:
talj //= kvot
summation += (talj // qfactor)
qfactor += 2
return summation
number_of_places = int(input("Enter the number of decimal places you want: "))
getcontext().prec = number_of_places
product = 10 ** number_of_places
result = 0
for multiplier, denominator in TERMS:
denominator = Decimal(denominator)
result += arctan(- denominator * multiplier, - (denominator ** 2))
result *= 4
string = str(result)
print(string[0:string.index("E")])
现在我们可以处理一个较大的
n
值:
> python3 test2.py
Enter the number of decimal places you want: 100
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
>