Taylor series with Python and Sympy: Revised
This article is originally published at http://firsttimeprogrammer.blogspot.com/
More than 2 years ago I wrote a short post on Taylor series. The post featured a simple script that took a single variable function (a sine in the example), printed out the Taylor expansion up to the nth term and plotted the approximation along with the original function. As you can see on the right on the “Popular posts” bar, that post is one of the most popular and I’m told it appears among the first results on Google.
The script I wrote originally was a bit clunky, and there surely was room for improvement. Last week I received an email from a reader, Josh, who sent me an improved version of the original post.
What has changed compared to the original post? Here is a short summary of the changes:
- Lambdify (from the sympy package) is used to speed up the computation.
- The plot function can now handle generic single variable functions and accepts arguments for more customized plotting behaviour.
I also made some improvements to the formatting, which was a bit horrible to say the least : )
Here is an approximation of the function log(x + 1) from the 1st up to the 9th order by steps of 2.
Note that the approximation is evaluated also for x <= 1 which does not make sense and should not be considered. Anyway, as expected, the farther you go from x0, the worse the approximation becomes. If you look closely in the output you’ll also see a warning since the evaluation of log(x + 1) in the region x <= 1 can not be done, but this doesn’t prevent the plot to be drawn.
You can find the improved version of the script here below. Thanks to Josh for taking the time to making it and sending it to me! You can find more about him at his GitHub profile.
Thanks for reading this post!
Thanks for visiting r-craft.org
This article is originally published at http://firsttimeprogrammer.blogspot.com/
Please visit source website for post related comments.