Approximating the sine function with Maclaurin Series using python
Have you ever wondered how your calculator can handle the sine, cosine and other operations that seems to be magically evaluated? Certainly there are more than one way, and to be honest I actually don't know which one my calculator uses, but here I will show one method that can compute a approximation of sine using python and a famous mathematical series.
The Maclourin Series
A Taylor series is a representation of a function as an infinite sum of terms that are calculated from the values of the function's derivatives at a single point.² when the Taylor series in centered at 0 (a=0) it got a new name: Maclaurin series.
The following rule define a Maclaurin series:
$f(x) = sum_0^infty (( f^(n)(0)) / (n!) )x^n = f(0) + (f'(0))/(1!) x + (f''(0))/(2!) x^2 + (f'''(0))/(3!) x^3 + ...$
The resolution, for $f(x) = sin(x)$ is:
$f(0) = sin(0) = 0$
$f'(0) = cos(0) = 1$
$f''(0) = -sin(0) = -0$
$f'''(0) = -cos(0) = -1$
doesn't matter how many times you derive sin(x), this pattern will repeat Ad infinitum
$ = 0 + (1x)/(1!) - (0x^2)/(2!) - (1x^3)/(3!) + (0x^4)/(4!) + (1x^5)/(5!) - (0x^6)/(6!) - (1x^7)/(7!) $
And as result we get a series that can compute the value of sin(x):
$sin (x) = x - x^3 / (3!) + x^5 / (5!) - x^7 / (7!) + x^9 / (9!) - ... = sum_0^infty(-1)^n x^(2n+1)/ ((2n+1)!)$
Solving it with python is simply a brute force task where you compute the series to the nth term necessary to get a precise value. Since it can be hard to know how many terms will be necessary, I tweaked the example to keep computing the series until it reaches a certain precision of the value provided by the math.sin() function from python default library.
by Ricardo Pascal on Aug. 3, 2015