无法确定pi的估计值

时间:2015-07-05 20:46:33

标签: python logic pi

我无法确定我的逻辑错误,

代码:

import math

repeat = "y"    
factor = [5]    

def findFactor():
    res = factor[0]
    factor[0] += 2
    print(res)
    return res

while (repeat == "y"):

    tol = float(input("Please enter the tolerance: "))

    z = 6/math.sqrt(3)
    print(z)

    num1 = 1
    num2 = num1 - (1/3)
    i = 2
    diff = 999

    while math.fabs(diff) > tol:
        diff = (z *num2) - (z * num1)
        print("Num 1", (z *num1), " Num 2", (z *num2))
        print("Pi: ", (z * num2))
        num1 = num2
        add = (-1)**i/(3**i * findFactor())
        print(add)
        num2 = num2 + add
        i += 1
        print("Diff", diff)
    print("We got: ", z * num2, " for pi")
    repeat = input("Continue? (Y/N)").lower()

它似乎在执行的开始工作,然后只是低于pi的方式。

Formula

1 个答案:

答案 0 :(得分:0)

错误在行中计算第二项:

try (FileReader reader = new FileReader(new File("/opt/Scheherazade/hegrid.git/hegrid-web/EventsJson.json"))) {
    JSONArray a = (JSONArray)parser.parse(reader);
}

但它应该是

num2 = num1 - (1/3)

用普通变量替换不必要的函数findFactor也会很好,每次迭代都会增加两次。