import math as m class Sum(object): def __init__(self, term, M, N): #self.term = term self.f_k = term self.M = M self.N = N def __call__(self, x): # calculate Taylor polynomial approximation s = 0 for k in range(self.M, self.N+1): s += self.f_k(k, x) return s def term(self, k, x): return self.f_k(k, x) def term(k, x): return (-x)**k def f_sin(j, x): return (-1)**j * (x**(2*j+1))/m.factorial(2*j + 1) def test_Sum(): def f(k, x): return x**k M = 0 N = 2 x = 0.5 expected = x**0 + x**1 + x**2 S = Sum(term=f, M=M, N=N) computed = S(x) tol = 1e-20 assert abs(expected - computed) < tol if __name__ == '__main__': print('a)') S = Sum(term, M=0, N=3) x = 0.5 print(S(x)) # calculate sum over f_k(x) for various k print(S.term(k=4, x=x)) # caluclate f_k(x) for specific k print('b)') a = test_Sum() if a is None: # or a == None, *almost* the same print('Test succeeded!') print('c)') N = 5 Taylor_sin = Sum(f_sin, M=0, N=N) x = m.pi # sin(x) = 0 expected = 0 result = Taylor_sin(x) print(result)