Python: Calculate sine/cosine with a precision of up to 1 million digits

前端 未结 3 1150
故里飘歌
故里飘歌 2020-12-19 14:24

Question is pretty self-explanatory. I\'ve seen a couple of examples for pi but not for trigo functions. Maybe one could use a Taylor series as done here but I\'m not entire

3条回答
  •  别那么骄傲
    2020-12-19 14:40

    Try this

    import math
    from decimal import *
    
    
    def sin_taylor(x, decimals):
        p = 0
        getcontext().prec = decimals
        for n in range(decimals):
            p += Decimal(((-1)**n)*(x**(2*n+1)))/(Decimal(math.factorial(2*n+1)))
        return p
    
    
    def cos_taylor(x, decimals):
        p = 0
        getcontext().prec = decimals
        for n in range(decimals):
            p += Decimal(((-1)**n)*(x**(2*n)))/(Decimal(math.factorial(2*n)))
        return p
    
    if __name__ == "__main__":
        ang = 0.1
        decimals = 1000000
        print 'sin:', sin_taylor(ang, decimals)
        print 'cos:', cos_taylor(ang, decimals)
    

提交回复
热议问题