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

我的梦境 提交于 2019-11-29 11:08:51

mpmath is the way:

from mpmath import mp
precision = 1000000
mp.dps = precision
mp.cos(0.1)

If unable to install mpmath or any other module you could try polynomial approximation as suggested.

where Rn is the Lagrange Remainder

Note that Rn grows fast as soon as x moves away from the center x0, so be careful using Maclaurin series (Taylor series centered in 0) when trying to calculate sin(x) or cos(x) of arbitrary x.

import math
x = .5
def sin(x):
    sum = 0
    for a in range(0,50): #this number (50) to be changed for more accurate results
        sum+=(math.pow(-1,a))/(math.factorial(2*a+1))*(math.pow(x,2*a+1))
    return sum

ans = sin(x)
print(str.format('{0:.15f}', ans)) #change the 15 for more decimal places

Here is an example of implementing the Taylor series using python as you suggested above. Changing to cos wouldn't be too hard after that.

EDIT:

Added in the formatting of the last line in order to actual print out more decimal places.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!