""" Ex. 7.12 from "A primer on..." Write a class for calculating a sum. The constructor should take the following parameters: - A function representing each term in the sum - The upper and lower bounds in the sum """ from math import factorial, pi 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 #a) make sure the following lines work: def term(k, x): return (-x)**k S = Sum(term, M=0, N=3) x = 0.5 print(S(x)) print(S.term(k=4, x=x)) # (-0.5)**4 #b) write a test function test_Sum: """ (Not done in lecture, but added here for completeness) We can use the case above for the test function, for which: expected = 1 - x + x**2 - x**3 = 1 - 0.5 + 0.25 - 0.125 = 0.625 """ def test_Sum(): tol = 1e-8 term = lambda k, x: (-x)**k s = Sum(term, M = 0, N = 3) computed = s(x = 0.5) expected = 0.625 assert abs(computed - expected) < tol test_Sum() #c) Taylor series for sin(x): def sin_term(k, x): return (-1)**k * x**(2 * k + 1) / factorial(2 * k + 1 ) #Taylor series with 11 terms: sin_approx = Sum(sin_term, 0, 10) print(sin_approx(pi)) """ Terminal> python Sum.py 0.625 0.0625 1.0348185903053497e-11 """