#a) class Sum: def __init__(self, fk, M, N): self.term = fk 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 fk(k, x): return (-x)**k S = Sum(fk, M=0, N=3) x = 0.5 print(S(x)) print(S.term(k=4, x=x)) # (-0.5)**4 #b) """How to test a class: 1. Make some choices of input data for the class 2. Create one or more instances 3. Test each function in the usual way, making suitable choices for the input arguments. """ def test_Sum(): #choose and define the input function to the class: def fk(k,x): return (-x)**k #create an instance with chosen input values (fk,M,N): S = Sum(fk,M=0,N=3) #test the methods of the class in the usual way tol = 1e-10 x = 0.5 k = 4 #the term method: expected1 = 0.0625 #(-0.5)**4 computed1 = S.term(k,x) assert abs(expected1-computed1) < tol #the __call__ method: expected2 = 1.0-x+(-x)**2+(-x)**3 computed2 = S(x) assert abs(expected2-computed2) < tol test_Sum() #c) """ Taylor term for sin(x): fk(k,x) = (-1)**k*(x**(2*k+1)/factorial(2*k+1)) """ from math import factorial,pi #define the term function def fk_sin(k,x): return (-1)**k*(x**(2*k+1)/factorial(2*k+1)) #create an instance of the Sum class with terms 0-10 taylor_sin = Sum(fk_sin,0,10) #print some results, should be very close to 0, 1, 0.5*sqrt(2): print(taylor_sin(pi),taylor_sin(pi/2),taylor_sin(pi/4))