迭代函数

时间:2015-03-13 02:21:38

标签: python function loops pi

我正在尝试编写一个计算pi值的函数。我想从函数中返回C和I的新值(以及π),然后使用新的C和I作为下一次迭代的输入。

这是我的代码:

def pi_func(I_i,C_i):

    C = (2*C_i*I_i)/(C_i+I_i)
    I = sqrt(C*I_i)
    pi = (C+I)/2

    print C
    print I

    return pi

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6

print pi_func(I_3,C_3)

好的,下面是我最新的代码。

def pi_func(I_i,C_i):

    new_C = (2*C_i*I_i)/(C_i+I_i)
    new_I = sqrt(new_C*I_i)
    pi = (new_C+new_I)/2

    print "C = ", new_C
    print "I = ", new_I

    return (pi,new_I,new_C)

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6
print "I = %r" %I_3
print "C = %r" %C_3

for i in xrange(100):
    x = pi_func(I_3,C_3)
    print "PI = %r" %x[0]
    I_3 = x[1]
    C_3 = x[2]


print "Here is the machine accuracy for pi: %r" % np.pi

我想获得机器精度:

Here is the machine accuracy for pi: 3.141592653589793

但我的计划给了我:PI = 3.141592653589792

因为我告诉我的程序要进行100次迭代,所以它会一直停止。但pi的值在第100次迭代之前计算得很好。

1 个答案:

答案 0 :(得分:2)

这似乎是迭代地完成工作:

from math import sqrt

def pi_func(I_i,C_i):

    C = (2*C_i*I_i)/(C_i+I_i)
    I = sqrt(C*I_i)
    pi = (C+I)/2

    print "C  = ", C
    print "I  = ", I

    return (pi, I, C)

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6
print "C3 = ", C_3
print "I3 = ", I_3

for i in xrange(10):
    x = pi_func(I_3,C_3)
    print "PI = ", x[0]
    I_3 = x[1]
    C_3 = x[2]

示例输出:

C3 =  5.19615242271
I3 =  2.59807621135
C  =  3.46410161514
I  =  3.0
PI =  3.23205080757
C  =  3.21539030917
I  =  3.10582854123
PI =  3.1606094252
C  =  3.1596599421
I  =  3.13262861328
PI =  3.14614427769
C  =  3.14608621513
I  =  3.13935020305
PI =  3.14271820909
C  =  3.14271459965
I  =  3.14103195089
PI =  3.14187327527
C  =  3.14187304998
I  =  3.14145247229
PI =  3.14166276113
C  =  3.14166274706
I  =  3.14155760791
PI =  3.14161017748
C  =  3.1416101766
I  =  3.14158389215
PI =  3.14159703438
C  =  3.14159703432
I  =  3.14159046323
PI =  3.14159374877
C  =  3.14159374877
I  =  3.141592106
PI =  3.14159292739

如果你想以递归的方式做,那就不是那么难了 - 主要的问题是何时停止递归。