""" Exercise 7.12 from "A primer on..." Make a class for summing a series. Main points: 1. Defining a function as an attribute to a class 2. Test functions for classes """ import numpy as np import matplotlib.pyplot as plt from math import factorial #a) Write the class Sum: 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 #b) A test function for the Sum class def test_Sum(): def term(k, x): return (-x)**k tol = 1e-10 S = Sum(term, M=0, N=3) x = 0.5 expected = 0.625 computed = S(x) assert abs(expected-computed) < tol if __name__ == "__main__": test_Sum() #c) use class Sum to compute the Taylor series of sin(x) #The term in the taylor series: def sin_term(k,x): return (-1)**k * x**(2*k + 1)/factorial(2*k +1) x = np.linspace(0, 4* np.pi) #Two instances of Sum, same term function but different number of terms: sin_approx1 = Sum(sin_term,0,2) sin_approx2 = Sum(sin_term,0,6) #plot both, as well as the exact solution: plt.axis([0, 4*np.pi, -1.1, 1.1]) plt.plot(x, sin_approx1(x)) plt.plot(x, sin_approx2(x)) plt.plot(x, np.sin(x)) plt.show() """ Terminal> python Sum.py (output is a plot) """