""" Exercise 7.12 in "A Primer on..." Implement a class for a sum: - user provides function for each term Attributes: - function for each term - lower and higher index of summation """ 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 print('a:') #following code should 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 print('b:') def test_Sum(): def f(k,x): return (-x)**k S = Sum(term = f, M=0, N=3) x = 0.5 expected = 1 - x + x**2 - x**3 computed = S(x) tol = 1e-10 assert abs(computed-expected) < tol test_Sum() print('c:') """ Terms in Taylor approximation of sin(x): (-1)**k*(x**(2*k+1))/factorial(2*k+1) """ from math import * def taylor_sin(k,x): return (-1)**k*(x**(2*k+1))/factorial(2*k+1) S = Sum(taylor_sin,0,5) print(S(pi/4),S(pi/2),S(pi)) """ Terminal> python Sum.py a: 0.625 0.0625 b: c: 0.7071067811796194 0.999999943741051 -0.00044516023820921277 """