""" Exercise 7.12 from "A primer on... Implement a class for computing a sum, where each term in the sum is given by a function passed as an argument to the constructor. A call method should compute and return the sum for a given argument x. """ from math import factorial, pi #a) Implementation of the class 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 #test code from the question text: 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) A test function for the class # (using the example above as the test case): def test_Sum(): S = Sum(term, M=0, N=3) x = 0.5 tol = 1e-8 expected_sum = 0.625 expected_term = 0.0625 assert abs(S(x)-expected_sum) < tol assert abs(S.term(4, x) - expected_term) < tol test_Sum() #c) Calculate the Taylor series approximation to sin(x), # for x = pi and a given N def term_sin(k, x): return (-1)**k / factorial(2 * k + 1) * x**(2 * k + 1) #test the approximation with N=6: sin_taylor = Sum(term_sin, M=0, N = 6) print(sin_taylor(pi))