#a) class Sum: def __init__(self,term, M, N): self.term = term self.M = M self.N = N def __call__(self,x): s = 0 for k in range(self.M,self.N+1): s += self.term(k,x) return s def term(k, x): return (-x)**k #a) S = Sum(term, M=0, N=3) x = 0.5 print(S(x)) print(S.term(k=4, x=x)) # (-0.5)**4 #b) def test_Sum(): tol = 1e-8 def term(k, x): return (-x)**k S = Sum(term, M=0, N=3) x = 0.5 expected = 1 - x + x**2 - x**3 computed = S(x) assert abs(computed-expected) < tol test_Sum() #c) """ Page 323 in "A primer on..." Terms in Taylor approximation of sin(x): (-1)**k*(x**(2*k+1))/factorial(2*k+1) """ from math import factorial,pi def sine_term(k,x): return (-1)**k*(x**(2*k+1))/factorial(2*k+1) for n in range(3,9): taylor_n = Sum(sine_term,M=0,N=n) print(f"With {n} terms: sin(pi) ~ {taylor_n(pi)}, sin(pi/2) ~ {taylor_n(pi/2)}") """ Terminal> python Sum.py 0.625 0.0625 With 3 terms: sin(pi) ~ -0.07522061590362306, sin(pi/2) ~ 0.9998431013994987 With 4 terms: sin(pi) ~ 0.006925270707505135, sin(pi/2) ~ 1.0000035425842861 With 5 terms: sin(pi) ~ -0.00044516023820921277, sin(pi/2) ~ 0.999999943741051 With 6 terms: sin(pi) ~ 2.1142567558399565e-05, sin(pi/2) ~ 1.0000000006627803 With 7 terms: sin(pi) ~ -7.727858894306387e-07, sin(pi/2) ~ 0.9999999999939768 With 8 terms: sin(pi) ~ 2.2419510716912098e-08, sin(pi/2) ~ 1.0000000000000437 """