In [10]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import factorial
np.set_printoptions(precision=2, suppress=True, linewidth=300)
In [11]:
# define the truncated sine expansion
def sinN(N):
    def evasinN(z):
        sinz = 0
        for k in np.arange(N+1):
            sinz += (-1)**k*z**(2*k+1)/factorial(2*k+1.)
        return sinz
    return evasinN
In [12]:
# the range for the evaluation
trange = np.linspace(0, 10.7, 18)
print('abscissa: ', trange)

# check the sine expansion for varying truncations
Nlist = [0, 1, 3, 5, 9]
plt.figure(2)
for N in Nlist:
    mysinN = sinN(N)
    sint = mysinN(trange)
    print('N={0}: '.format(N), sint)
    # cut off values beyond 5
    cutoff = np.abs(sint) > 5
    sint[cutoff] = None
    plt.plot(trange, sint, label='N={0}'.format(N))

# the "real" function values
sint = np.sin(trange)
plt.figure(2)
print('real sine: '.format(N), sint)
plt.plot(trange, sint, label='sine')

# show the plot
plt.legend()
plt.show()
abscissa:  [  0.     0.63   1.26   1.89   2.52   3.15   3.78   4.41   5.04   5.66   6.29   6.92   7.55   8.18   8.81   9.44  10.07  10.7 ]
N=0:  [  0.     0.63   1.26   1.89   2.52   3.15   3.78   4.41   5.04   5.66   6.29   6.92   7.55   8.18   8.81   9.44  10.07  10.7 ]
N=1:  [   0.      0.59    0.93    0.77   -0.14   -2.05   -5.2    -9.85  -16.24  -24.63  -35.26  -48.39  -64.26  -83.12 -105.22 -130.82 -160.15 -193.47]
N=3:  [    0.       0.59     0.95     0.95     0.57    -0.08    -0.97    -2.41    -5.55   -13.16   -30.59   -67.12  -137.64  -264.69  -480.98  -832.35 -1381.25 -2210.76]
N=5:  [    0.       0.59     0.95     0.95     0.58    -0.01    -0.6     -0.99    -1.14    -1.44    -3.26   -10.29   -31.53   -87.39  -221.37  -520.84 -1152.17 -2417.55]
N=9:  [  0.     0.59   0.95   0.95   0.58  -0.01  -0.59  -0.95  -0.95  -0.58   0.01   0.59   0.91   0.69  -0.61  -4.97 -19.41 -66.66]
real sine:  [ 0.    0.59  0.95  0.95  0.58 -0.01 -0.59 -0.95 -0.95 -0.58  0.01  0.6   0.96  0.95  0.58 -0.02 -0.6  -0.96]