Taylor Series Coefficients in python

496 Views Asked by At

I am trying to get the coefficients of a Taylor Series in an array. I need the value of the coefficients for an arbitrary function.

There are two ways I am trying, but I do not know which one is the correct one. Can anyone help me?

Here is my code

def function(x):
  return swish(x)


def Maclaurin(func, n, order):
    coefficients = []
    for i in range(order+1):
      coefficients.append(((-1)**i * (func(i))**(2*i+1)) / np.math.factorial(2*i+1)) #first try
      coefficients.append(func(i) / math.factorial(i)) #second try
    return coefficients

print(Maclaurin(function, 0, 3))
1

There are 1 best solutions below

0
duffymo On

Here are example implementations of sine and cosine Taylor series in Python that don't require calls to a factorial function.

import math
import matplotlib.pyplot as plt

# https://stackoverflow.com/questions/75389200/taylor-series-coefficients-in-python/75413512#75413512

def cosine(t, n):
    result = 0.0
    term = 1.0
    sign = 1.0
    for i in range(0, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i+1)/(2*i+2)
    return result

def sine(t, n):
    result = 0.0
    term = t
    sign = 1.0
    for i in range(1, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i)/(2*i+1)
    return result
    
if __name__ == '__main__':
    npoints = 180
    nterms = 50
    dt = 2.0*math.pi/npoints
    t = [i*dt for i in range(0, npoints)]
    cf = [cosine(t[i], nterms) for i in range(0, npoints)]
    sf = [sine(t[i], nterms) for i in range(0, npoints)]
    cf_error = [cf[i] - math.cos(t[i]) for i in range(0, npoints)]
    sf_error = [sf[i] - math.sin(t[i]) for i in range(0, npoints)]
    plt.plot(t, cf, color='blue', linewidth=2, label='cosine')
    plt.plot(t, sf, color='red', linewidth=2, label='sine')
#    plt.plot(t, cf_error, color='green', linewidth=2, label='cosine error')
#    plt.plot(t, sf_error, color='black', linewidth=2, label='sine error')
    plt.show()

Here's how I'd do the Maclaurin series using SymPy:

import sympy as sp
from sympy import Function, Symbol

def maclaurin(f, x, n):
    coefficients = []
    numer = f(x)
    coefficients.append(numer)
    denom = 1.0
    for i in range(1, n):
        denom *= i
        numer = sp.diff(numer/denom, x)
        coefficients.append(numer)
    return coefficients

if __name__ == '__main__':
    # try out the Maclaurin series and SymPy
    x = Symbol('x')
    f = Function('f')
    series = maclaurin(f, x, 5)
    print(series)

As Mark Dickerson pointed out, the Maclaurin series expands a function about a point x = 0. This function gives you a list of coefficients that will have to be evaluated and summed to give you the value. The Taylor series for sine and cosine above include plots of error. Note that the errors become larger the further you get from the point x = 0. Series expansions aren't intended to wander far away from their expansion point.