Created
August 4, 2017 16:50
-
-
Save mick001/6e141072685278148f82f60895f4e537 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
func_lambda = sy.lambdify(x, f, "numpy") | |
# 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) | |
y = func_lambda(x1) | |
plt.plot(x1, y, 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment