1000 digits of pi in Python

前端 未结 11 1460
忘了有多久
忘了有多久 2020-11-28 10:54

I have been thinking about this issue and I can\'t figure it out. Perhaps you can assist me. The problem is my code isn\'t working to output 1000 digits of pi in the Python

11条回答
  •  隐瞒了意图╮
    2020-11-28 11:13

    From Fabrice Bellard site: Pi Computation algorithm. Sorry for such a straightforward implementation. 1000 is fast enough (0.1s for me), but 10000 isn't such fast - 71s :-(

    import time
    from decimal import Decimal, getcontext
    
    def compute(n):
        getcontext().prec = n
        res = Decimal(0)
        for i in range(n):
            a = Decimal(1)/(16**i)
            b = Decimal(4)/(8*i+1)
            c = Decimal(2)/(8*i+4)
            d = Decimal(1)/(8*i+5)
            e = Decimal(1)/(8*i+6)
            r = a*(b-c-d-e)
            res += r
        return res
    
    if __name__ == "__main__":
        t1 = time.time()
        res = compute(1000)
        dt = time.time()-t1
        print(res)
        print(dt)
    

提交回复
热议问题