新手在这里:
刚刚学习Python,这个让我烦恼。它提出了一个手动计算Pi的功能,Madhava way. - 也称为练习#16从这里开始:http://interactivepython.org/courselib/static/thinkcspy/Functions/thinkcspyExercises.html
有人可以看看我的混乱和过于复杂的代码并告诉我,我是否遗漏了什么?非常感谢。 (首先查看维基页面上的等式,否则我的代码将毫无意义 - 好吧,它仍然可能没有。)
import math
def denom_exp(iters):
for i in range(0, iters):
exp = 3^iters
return exp
def base_denom(iters):
for i in range(0, iters):
denom = 1 + 2*iters
return denom
def myPi(iters):
sign = 1
pi = 0
for i in range(0, iters):
pi = pi + sign*(1/((base_denom(iters))*denom_exp(iters)))
sign = -1 * sign
pi = (math.sqrt(12))*pi
return pi
thisisit = myPi(10000)
print(thisisit)
答案 0 :(得分:4)
尝试使用此代码,手动计算Pi,Madhava方式。
import math
def myPi(iters):
sign = 1
x = 1
y = 0
series = 0
for i in range (iters):
series = series + (sign/(x * 3**y))
x = x + 2
y = y + 1
sign = sign * -1
myPi = math.sqrt(12) * series
return myPi
print(myPi(1000))