Saturday, 14 March 2015

Taylor series with Python and Sympy

Here I am again using my beloved Python and doing maths stuff.

Today I’d like to post a short piece of code I made after a review of Taylor series I did. This script lets you input (almost) any function, provided that it can be represented using Sympy and output the Taylor series of that function up to the nth term centred at x0.

Sympy is a great module for basic symbolic mathematics, it works fine and it is really simple to use even if you are new to Python.

Here is the output of the plot function for the function sin(x) approximating up to the 9th term:

figure_1

# >>>
# Taylor expansion at n=1 x
# Taylor expansion at n=3 -x**3/6 + x
# Taylor expansion at n=5 x**5/120 - x**3/6 + x
# Taylor expansion at n=7 -x**7/5040 + x**5/120 - x**3/6 + x
# Taylor expansion at n=9 x**9/362880 - x**7/5040 + x**5/120 - x**3/6 + x

Note that in the console output the series is written backwards, however I think it could be fixed.

Here is the code I used

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

This code can be customized to return Taylor expansions for any function you’d like to use (of course provided it can be represented using Sympy).

Finally, the code used to generate the plot

# Plot results
def plot():
x_lims = [-5,5]
x1 = np.linspace(x_lims[0],x_lims[1],800)
y1 = []
# Approximate up until 10 starting from 1 and using steps of 2
for j in range(1,10,2):
func = taylor(f,0,j)
print('Taylor expansion at n='+str(j),func)
for k in x1:
y1.append(func.subs(x,k))
plt.plot(x1,y1,label='order '+str(j))
y1 = []
# Plot the function to approximate (sine, in this case)
plt.plot(x1,np.sin(x1),label='sin of x')
plt.xlim(x_lims)
plt.ylim([-5,5])
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.title('Taylor series approximation')
plt.show()
plot()

27 comments:

  1. Replies
    1. Thanks! I'm glad you liked it! :)

      Delete
    2. The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download Now

      >>>>> Download Full

      The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download LINK

      >>>>> Download Now

      The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download Full

      >>>>> Download LINK 1i

      Delete
  2. How do you define what h is in the tailor series for this code?

    ReplyDelete
    Replies
    1. Hi, could you please explain your question? I can't find any h in the code

      Delete
  3. Do you have some examples for multivariable function

    ReplyDelete
  4. Do you mind if I use the code for my final project in a math course I am taking?

    ReplyDelete
    Replies
    1. Not at all, just please reference this article if you can.

      Delete
  5. Replies
    1. Just typing taylor(f,0,j) in the Python interpreter should print it out in this example.

      Delete
  6. I appreciate your work. Thanks!

    ReplyDelete
  7. how can i use custom function with 3 dimensions like 2x^2+6y^2-z^2=0?

    ReplyDelete
  8. Thank you! Just started to learn taylor series, and your work is really helpful.

    ReplyDelete
  9. Hi.
    Plz help me for projectile motion sorce code in python.

    ReplyDelete
  10. This Page is about Sector Wise Projects in Bahadurgarh.... 123movies

    ReplyDelete
  11. sad shayari image Such a wonderful article and I feel that it is best to write more on this topic. Thank you so much because i learn a lot of ideas about it. Keep posting...

    ReplyDelete
  12. Thank you so much for sharing this amazing blog with us. Anyone who are searching for more, free training's like Python, Java, Asp.Net, Nodejs and more programming languages please contact Nareshit.
    NodeJS Online Training

    ReplyDelete
  13. Hi can you suggest how I can use the above program to plot taylor expansion for a function (x^2)/20

    ReplyDelete
    Replies
    1. Can you modify line 10 in the first code from sin() to your function?

      Delete
  14. Hi can you suggest how I can use the above program to plot taylor expansion for a function (x^2)/20

    ReplyDelete
  15. With so many books and articles coming up to give gateway to make-money-online field and confusing reader even more on the actual way of earning money, programmer socks

    ReplyDelete
  16. thanks for sharing such a wonderful information from this post
    Programmer Socks

    ReplyDelete
  17. The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download Now

    >>>>> Download Full

    The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download LINK

    >>>>> Download Now

    The Beginner Programmer: Taylor Series With Python And Sympy >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete