Skip to content

Instantly share code, notes, and snippets.

@mick001
Last active March 5, 2022 07:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mick001/7c4741961a72d69f880d0c602c833fcf to your computer and use it in GitHub Desktop.
Save mick001/7c4741961a72d69f880d0c602c833fcf to your computer and use it in GitHub Desktop.
Revised and improved version of Taylor series with Python and Sympy. You can find the original post at http://firsttimeprogrammer.blogspot.com/2015/03/taylor-series-with-python-and-sympy.html
import sympy as sy
import numpy as np
from sympy.functions import sin, cos, ln
import matplotlib.pyplot as plt
plt.style.use("ggplot")
# Factorial function
def factorial(n):
if n <= 0:
return 1
else:
return n * factorial(n - 1)
# Taylor approximation at x0 of the function 'function'
def taylor(function, x0, n, x = sy.Symbol('x')):
i = 0
p = 0
while i <= n:
p = p + (function.diff(x, i).subs(x, x0))/(factorial(i))*(x - x0)**i
i += 1
return p
def plot(f, x0 = 0, n = 9, by = 2, x_lims = [-5, 5], y_lims = [-5, 5], npoints = 800, x = sy.Symbol('x')):
x1 = np.linspace(x_lims[0], x_lims[1], npoints)
# Approximate up until n starting from 1 and using steps of by
for j in range(1, n + 1, by):
func = taylor(f, x0, j)
taylor_lambda = sy.lambdify(x, func, "numpy")
print('Taylor expansion at n=' + str(j), func)
plt.plot(x1, taylor_lambda(x1), label = 'Order '+ str(j))
# Plot the function to approximate (sine, in this case)
func_lambda = sy.lambdify(x, f, "numpy")
plt.plot(x1, func_lambda(x1), label = 'Function of x')
plt.xlim(x_lims)
plt.ylim(y_lims)
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.title('Taylor series approximation')
plt.show()
# Define the variable and the function to approximate
x = sy.Symbol('x')
f = ln(1 + x)
plot(f)
##########################################################################
# OUTPUT
##########################################################################
#
# RuntimeWarning: invalid value encountered in log
#
# Taylor expansion at n=1 x
# Taylor expansion at n=3 x**3/3 - x**2/2 + x
# Taylor expansion at n=5 x**5/5 - x**4/4 + x**3/3 - x**2/2 + x
# Taylor expansion at n=7 x**7/7 - x**6/6 + x**5/5 - x**4/4 + x**3/3 - x**2/2 + x
# Taylor expansion at n=9 x**9/9 - x**8/8 + x**7/7 - x**6/6 + x**5/5 - x**4/4 + x**3/3 - x**2/2 + x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment