-->

Writing a Python function to calculate Pi

2019-08-06 11:46发布

问题:

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