Skip to content

Instantly share code, notes, and snippets.

@mick001
Created August 29, 2015 10:34
Show Gist options
  • Save mick001/277d1403ad4b4cfaf171 to your computer and use it in GitHub Desktop.
Save mick001/277d1403ad4b4cfaf171 to your computer and use it in GitHub Desktop.
Taylor series with Python and Sympy part 2. Full article at http://www.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
import matplotlib.pyplot as plt
plt.style.use("ggplot")
# Define the variable and the function to approximate
x = sy.Symbol('x')
f = sin(x)
# 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):
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment