
# sinMac.py
# Andrew Davison, ad@coe.psu.ac.th, June 2026

'''
Generate multiple Maclaurin series approximations to
sin(x) using 3, 5, 7, and 9 terms.

Plot sin(x) and the series over the x interval
[\pi, \pi] to see how well the series deal with 
approximating the function.

Each of the series is also printed to stdout, so their
coefficients can be examined.

See sinFar.py for a version of this code which deals with
a larger number of terms, and a wider x range.
'''

import math
import matplotlib.pyplot as plt
import faUtils
import sympy as sp


xs = faUtils.linspace(-math.pi, math.pi, 200)

plt.figure()

for n in [3,5,7,9]:
  print(f"\nUsing {n} terms:")
  fCoeffs = faUtils.seriesCoefs(sp.sin, nTerms=n,
                                   verbose=True)
  ys = [ faUtils.evalPowers(fCoeffs, x) for x in xs]
  plt.plot(xs, ys, label= str(n) + " Terms")


mathFn = [math.sin(x) for x in xs]
plt.plot(xs, mathFn, 'k', label='sin(x)', ls='dashed')

plt.grid()
plt.title('Maclaurin Series sin(x) Approx')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()