Leibniz formula for π - Is this any good? (Python)

前端 未结 7 970
北恋
北恋 2021-01-03 16:15

I\'m doing an exercise that asks for a function that approximates the value of pi using Leibniz\' formula. These are the explanations on Wikipedia:

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 16:51

    This was my approach:

    def estPi(terms):
        outPut = 0.0
        for i in range (1, (2 * terms), 4):
            outPut = (outPut + (1/i) - (1/(i+2)))
        return 4 * outPut
    

    I take in the number of terms the user wants, then in the for loop I double it to account for only using odds.

    at 100 terms I get        3.1315929035585537
    at 1000 terms I get       3.140592653839794
    at 10000 terms I get      3.1414926535900345
    at 100000 terms I get     3.1415826535897198
    at 1000000 terms I get    3.1415916535897743
    at 10000000 terms I get   3.1415925535897915
    at 100000000 terms I get  3.141592643589326
    at 1000000000 terms I get 3.1415926525880504
    Actual Pi is              3.1415926535897932
    

    Got to love a convergent series.

提交回复
热议问题