how to calculate sine and cosine in python without using math
Good time of day! Here's the thing:
There is a need to accurately calculate the sine and cosine, with the possibility of changing the accuracy(as decimal.getcontext().prec=...).
Math, of course, does not provide such a possibility.
I honestly don't know which way to go at all
0
2 answers
The documentation for the decimal module contains examples of calculating sin, cos:
def sin(x):
"""Return the sine of x as measured in radians.
The Taylor series approximation works best for a small value of x.
For larger values, first compute x = x % (2 * pi).
>>> print(sin(Decimal('0.5')))
0.4794255386042030002732879352
>>> print(sin(0.5))
0.479425538604
>>> print(sin(0.5+0j))
(0.479425538604+0j)
"""
getcontext().prec += 2
i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
getcontext().prec -= 2
return +s
2
Author: jfs, 2018-04-07 08:09:41
The best thing I found was the Taylor series.
Here's the function, if you're interested:
def q(x):
Decimal(x)
def sin(x):
tmp=getcontext().prec
getcontext().prec=tmp+50
x=q(x)
n=x
r = 0;
i = 1;
while ((-n,n)[n>0] > q("1E-"+str(getcontext().prec))):
r += n;
n *= q(-1) * x * x / ((2 * i) * (2 * i + 1));
i+=1
getcontext().prec=tmp
return q(r)
1
Author: Михаил, 2017-12-03 14:33:11