Python: calculates sine / cosine to 1 million digits precision
The question is pretty clear. I've seen some examples for pi, but not trigo functions. It might be possible to use the Taylor series as done here , but I'm not really sure how to implement this in python. Especially how to store so many numbers. I have to mention: this will work perfectly in vanilla python, i.e. without numpy, etc.
Thank!
Edit: as said, I know the question has been asked before, but it's in java and I was looking for a python implementation :)
Edit 2: wow I didn't know the people here could get so absorbed. I tried several approaches but none worked. I thought this was the place where you can ask for advice, I guess I was wrong.
Last edit: for those who might find this helpful: many angles can be calculated as multiples of sqrt (2), sqrt (3) and Phi (1.61803). Since these numbers are widely available with 10mio precision, it is useful to have them in a file and read them directly into your program
source to share
mpmath is the way:
from mpmath import mp
precision = 1000000
mp.dps = precision
mp.cos(0.1)
If you can't install mpmath or any other module, you can try polynomial approximation as suggested.
where Rn is the Lagrangian remainder
Note that Rn grows rapidly as soon as x moves away from the center x 0so be careful when using the Maclaurin series (Taylor series centered at 0) when trying to compute sin (x) or cos (x) of an arbitrary x.
source to share
try it
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)
source to share
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 implementation of the Taylor series using python as you said above. After that, changing to cos would not be too hard.
EDIT:
Added to last line formatting to actually print more than decimal places.
source to share