Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import numpy as np
- import matplotlib.pyplot as plt
- def taylor(k,a,x):
- sum = 0
- result = 0
- denominator = 0
- numerator = 0
- for i in range(0, k + 1):
- # Calculate ith derivative of f(x) = e^x, evaluated at e^x
- result = np.exp([a])[0]
- # Calculate i!
- denominator = math.factorial(i)
- # Calculate (x-a)^i
- numerator = math.pow((x-a), i)
- result = result * (float(numerator) / denominator)
- sum = sum + result
- return sum
- # define X range
- X = np.linspace(-4.,4.,160)
- # set X and Y axis of plot
- axes = plt.gca()
- axes.set_xlim([-4.,4.])
- axes.set_ylim([-5.,50.])
- #define taylor_vals and error_vals
- n = len(X)
- taylor_vals = np.zeros((5,n))
- error_vals = np.zeros((5,n))
- # Here add code to compute taylor_vals and error_vals
- # Call taylor for each X[i]
- for i in range(0, n):
- true_val = np.exp([X[i]])[0]
- for j in range(0, 5):
- taylor_vals[j][i] = taylor(j, 1.0, X[i])
- error_vals[j][i] = math.fabs(true_val - taylor_vals[j][i])
- #print("True: " + str(true_val) + "Approximated: " + str(taylor_vals[j][i]))
- #plotting code
- plt.plot(X,[np.exp(x) for x in X],'bo',label = 'true value')
- # create plots of Taylor expansions here
- # Plot a curve for each of the 6 approximations
- for j in range(0, 5):
- plt.plot(X,taylor_vals[j], label = 'approximation value')
- #plots for errors come here
- print("X shape" + str(X.shape))
- print("error[0] shape" + str(error_vals[0].shape))
- for j in range(0, 5):
- plt.semilogy(X,error_vals[j])
- plt.figure()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement