Writing a Python function to calculate Pi

我只是一个虾纸丫 提交于 2019-12-13 02:13:22

问题


newbie here:

Just learning Python and this one has me pooped. It's coming up with a function for manually computing Pi, the Madhava way. - Also known as exercise #16 from here: http://interactivepython.org/courselib/static/thinkcspy/Functions/thinkcspyExercises.html

Can somebody take a look at my discombobulated and overly complex code and tell me if I'm missing something? Much thanks. (look at the equation on the wiki page first, otherwise my code will make no sense - well, it still may not.)

 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)

回答1:


Try this code, manually computing Pi, the Madhava way.

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


来源:https://stackoverflow.com/questions/29190407/writing-a-python-function-to-calculate-pi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!