python函数编程求三个数_编写一个Python函数来计算Pi

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)

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值