这是编程课程的一项任务。我们需要使用两个不同的函数来近似π。1使用Gregory理论,另一个是Sangamagrama的Madhava。这两个都不是问题,但第三个功能是给我一些麻烦。:
检查两个序列中哪一个收敛最快。使用此序列编写函数approach_pi。此函数应允许确定π的逼近值,即精确到n小数。n值应作为函数的参数。要确定该方法的准确性,您应该检查序列中两个连续的项之间的差值是否小于10^-n-1。当(i-1)th与 i-th 项的差值小于10^-n-1时,I-部分和精确地形成了π对(n)小数的逼近。函数应该给出元组(i,p),i是计算项的个数,n是π的逼近值。
以下是我的代码:
def GL(n):
a, pi, flag = 1, 0, True
while a <= (n*2-1):
if flag:
pi += (4/a)
else:
pi -= (4/a)
flag = not flag
a += 2
return pi
def MvS(n):
flag, a, parentheses, i = True, 3, 1, 1
while a <= (n*2-1):
if flag:
parentheses -= (1/(a*3**i))
else:
parentheses += (1/(a*3**i))
i += 1
a += 2
flag = not flag
return math.sqrt(12)*parentheses
def approach_pi(n):
counter_GL, counter_MvS, i = 0, 0, 2
while 10**(-n-1) > GL(i-1) - GL(i) > (-10**(-n-1)):
counter_GL += 1
i += 1
i = 2
while 10**(-n-1) > MvS(i-1) - MvS(i) > (-10**(-n-1)):
counter_MvS += 1
i += 1
return counter_GL, counter_MvS, GL(i)
x = int(input("give n : "))
print(approach_pi(x))我知道最后一个函数一点也不正确,但我没有想法了。有人能给我解释一下这个问题的正确理由吗?
一些示例解决方案是: approach_pi(3):(10,3.14159051093808) approach_pi(2):(8,3.141568715941784) approach_pi(6):(16,3.1415926517339976)
发布于 2021-11-01 21:16:18
如果将函数构建为生成器,这将变得更加高效,因此不必每次都重新运行整个序列。
计算的紧密性只是一个if abs(this - lastthis) < epsilon的问题。
这似乎是可行的,它显示了方法有多么糟糕:
import math
def GL():
a, pi, flag = 1, 0, True
while True:
if flag:
pi += (4/a)
else:
pi -= (4/a)
flag = not flag
a += 2
yield pi
def MvS():
flag, a, parentheses, i = True, 3, 1, 1
yield 3
while True:
if flag:
parentheses -= (1/(a*3**i))
else:
parentheses += (1/(a*3**i))
i += 1
a += 2
flag = not flag
yield math.sqrt(12)*parentheses
def approach_pi(n):
epsilon = 10**(-n)
oldg = 0
oldm = 0
for i,gm in enumerate(zip(GL(), MvS())):
g,m = gm
print(i,g,m)
if abs(g-oldg) < epsilon:
print( "GL converges at step", i )
return i+1,g
if abs(m-oldm) < epsilon:
print( "MvS converges at step", i )
return i+1,m
oldg,oldm = g,m
approach_pi(6)您可以通过展开循环来消除“标志”:
import math
def GL():
a, pi = 1, 0
while True:
pi += (4/a)
a += 2
yield pi
pi -= (4/a)
a += 2
yield pi
def MvS():
parentheses, a, denom = 1, 3, 3
yield 3
while True:
parentheses -= (1/(a*denom))
a += 2
denom *= -3
yield math.sqrt(12)*parentheses
def approach_pi(n):
epsilon = 10**(-n)
oldg = 0
oldm = 0
for i,gm in enumerate(zip(GL(), MvS())):
g,m = gm
print(i,g,m)
if abs(g-oldg) < epsilon:
print( "GL converges at step", i )
return i+1,g
if abs(m-oldm) < epsilon:
print( "MvS converges at step", i )
return i+1,m
oldg,oldm = g,m
approach_pi(6)https://stackoverflow.com/questions/69802773
复制相似问题