
# chebExp.py
# Andrew Davison, ad@coe.psu.ac.th, June 2026
'''
Code for the Chebyshev question at the end of
the Function Approximations chapter.

4. Using a Maclaurin polynomial for $xe^x$, 
obtain a small degree Chebyshev polynomial 
approximation while keeping the error less 
than $0.01$ on $[-1, 1]$.
'''

import math
import faUtils

def f(x):
  return x * math.exp(x)


nTerms = 5   # 4, 5, 6 
a = -1; b = 1
print(f"Evaluating f(x) using {nTerms} terms in [{a},{b}]:")
coefs = faUtils.chebFit(a, b, nTerms, f)
faUtils.printCoefs(coefs)

print(f"    x            actual       chebyshev     abs error")
xs = faUtils.linspace(-1, 1, 10)
for x in xs:
  chebx = faUtils.chebEval(a, b, coefs, nTerms, x)
  print(f"{x:12.6f} {f(x):12.6f} {chebx:12.6f}  {abs(f(x) - chebx):12.6f}")

