#! /usr/bin/env python # -*- coding: utf-8 -*- """ Solution for the problem 2 of the last CS101 lab assignment sheet. Plotting the exponential function and its 5 first Taylor approximation (on the same graph). @date: Wed April 22 10:31:45 2015. @author: Lilian Besson for CS101 course at Mahindra Ecole Centrale 2015. @licence: GNU Public License version 3. """ import numpy as np import matplotlib.pyplot as plt from math import factorial # The function and point we are interested about def f(x): return np.exp(x) x0 = 0.0 def taylor_exp(x0, n, x): """ Return $T_n(exp, x_0)(x)$, the Taylor expansion of order n for the function exponential, at the point x_0, for x.""" y = (x - x0)**0 for k in xrange(1, n+1): y += f(x0) * (x - x0)**k / factorial(k) return y # Samples for the X axis X = np.linspace(-3, 2, 500) # New figure plt.figure() # Move spines ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) # Plot exp(x) plt.plot(X, f(X), color="black", linewidth=3, label=r"$\exp(x)$") # Plot the successive Taylor expansion (can go up to 5 or more!) for n in xrange(0, 4): plt.plot(X, taylor_exp(x0, n, X), label=(r"$T_" + str(n) + "(\exp, x_0)(x)$")) # Title, xlabel and ylabel plt.title("The exponential function and its first 4 Taylor approximation.") plt.xlabel(r"Values for $x$") plt.ylabel(r"Values for $y$") # Add a legend (using the label of each plot), and show to graph plt.legend(loc="upper left") #plt.show() plt.savefig("Plotting_Taylor_approximation_for_exp_of_x.png", dpi=240) plt.savefig("Plotting_Taylor_approximation_for_exp_of_x.pdf", dpi=240) # End of the Python source for Plotting_Taylor_approximation_for_exp_of_x.py