新手在这里:

仅学习Python,这便使我大便了。它提供了一个用于手动计算Pi的功能,Madhava way.-从此处也称为练习#16:http://interactivepython.org/courselib/static/thinkcspy/Functions/thinkcspyExercises.html

有人可以看一下我发现的,过于复杂的代码,并告诉我是否遗漏了什么吗?非常感谢。 (首先查看Wiki页面上的等式,否则我的代码将毫无意义-好的,可能仍然没有。)

 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)

最佳答案

尝试以下代码,以Madhava方式手动计算Pi。

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))

关于python - 编写Python函数以计算Pi,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29190407/

10-11 04:25