Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import math
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. def taylor(k,a,x):
  6. sum = 0
  7. result = 0
  8. denominator = 0
  9. numerator = 0
  10. for i in range(0, k + 1):
  11. # Calculate ith derivative of f(x) = e^x, evaluated at e^x
  12. result = np.exp([a])[0]
  13. # Calculate i!
  14. denominator = math.factorial(i)
  15. # Calculate (x-a)^i
  16. numerator = math.pow((x-a), i)
  17. result = result * (float(numerator) / denominator)
  18. sum = sum + result
  19.  
  20. return sum
  21.  
  22. # define X range
  23. X = np.linspace(-4.,4.,160)
  24.  
  25. # set X and Y axis of plot
  26. axes = plt.gca()
  27. axes.set_xlim([-4.,4.])
  28. axes.set_ylim([-5.,50.])
  29.  
  30. #define taylor_vals and error_vals
  31. n = len(X)
  32. taylor_vals = np.zeros((5,n))
  33. error_vals = np.zeros((5,n))
  34.  
  35. # Here add code to compute taylor_vals and error_vals
  36.  
  37. # Call taylor for each X[i]
  38. for i in range(0, n):
  39. true_val = np.exp([X[i]])[0]
  40. for j in range(0, 5):
  41. taylor_vals[j][i] = taylor(j, 1.0, X[i])
  42. error_vals[j][i] = math.fabs(true_val - taylor_vals[j][i])
  43. #print("True: " + str(true_val) + "Approximated: " + str(taylor_vals[j][i]))
  44.  
  45. #plotting code
  46. plt.plot(X,[np.exp(x) for x in X],'bo',label = 'true value')
  47.  
  48. # create plots of Taylor expansions here
  49. # Plot a curve for each of the 6 approximations
  50. for j in range(0, 5):
  51. plt.plot(X,taylor_vals[j], label = 'approximation value')
  52.  
  53. #plots for errors come here
  54. print("X shape" + str(X.shape))
  55. print("error[0] shape" + str(error_vals[0].shape))
  56.  
  57. for j in range(0, 5):
  58. plt.semilogy(X,error_vals[j])
  59. plt.figure()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement