Evaluate the $\sin$ function from its series representation $$ \sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \dots $$
A naive algorithm is to sum the series up to the $N$th term: $$ \sin x \approx \sum_{n=1}^N \frac{(-1)^{n-1} x^{2n-1}}{(2n - 1)!} $$
Problems:
Better approach: Build up series terms $a_n$ using previous term $a_{n-1}$ through a recursion:
\begin{align} a_n &= a_{n-1} \times q_n\\ a_n &= \frac{(-1)^{n-1} x^{2n-1}}{(2n - 1)!} = \frac{(-1)^{n-2} x^{2n-3}}{(2n - 3)!} \frac{-x^2}{(2n - 1)(2n - 2)}\\ a_n & = a_{n-1} \frac{-x^2}{(2n - 1)(2n - 2)} \end{align}Accuracy of this approach? Not clear in absolute terms but we can make the assumption that the error is approximately the last term in the sum, $a_N$. Hence we can strive to make the relative error smaller than the machine precision $$ \left| \frac{a_N}{\sum_{n=1}^N a_n} \right| < \epsilon_m $$
In file series.py
implement a function sin_recursive(x, N=100)
that
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Import your series.py
as a module:
import series
NOTE: If you changed code in series
you will need to reload the module: execute the following cell whenever you changed series.py
.
from importlib import reload
reload(series)
<module 'series' from '/Volumes/ASU/oliver/Documents/Teaching/ASU/CompPhys_PHY494/2021/PHY494-resources/08_errors/erroranalysis/series.py'>
Test the implementation against the "exact" numpy function np.sin()
and show the relative error as a function of $1 \le N < 1000$.
Report and plot
x =
$\pi/3, 2\pi, 7.89\pi, -12.3\pi, 14.78\pi$abs(sin_series(x) - sin(x))/abs(sin(x))
as function of $N$(Use a log-log plot.)
Implementation of the error calculation against the numpy reference implementation np.sin
:
def relerror_sin(N_values, x):
# TODO
pass
Plot for $x = \pi/3$ and for $x = -7.89\pi$
Plot all x values: