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

前端 未结 7 952
北恋
北恋 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

    Using pure Python you can do something like:

    def term(n):
        return ( (-1.)**n / (2.*n + 1.) )*4.
    
    def pi(nterms):
        return sum(map(term,range(nterms)))
    

    and then calculate pi with the number of terms you need to reach a given precision:

    pi(100)
    # 3.13159290356
    
    pi(1000)
    # 3.14059265384
    

提交回复
热议问题