Tom_Jung

Untitled

Jun 9th, 2019
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. #Math UBC / Numerical Differentiation
  2.  
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. #%matplotlib online
  6.  
  7. def derivative(f, a, method, h):
  8. """
  9. Compute the difference formula for f'(a) with step h.
  10.  
  11. Parameters
  12. ----------
  13. f : function
  14. Vectorized function of one variable
  15. a : number
  16. Compute derivative at x = a
  17. method : string
  18. Difference formula: 'forward', 'backward' or 'central'
  19. h : number
  20. Step size in difference formula
  21.  
  22. Returns
  23. -------
  24. float
  25. Difference formula:
  26. central: f(a+h) - f(a-h))/2h
  27. forward: f(a+h) - f(a))/h
  28. backward: f(a) - f(a-h))/h
  29. """
  30. if method == 'central':
  31. return (f(a+h) - f(a-h))/2*h
  32. elif method == 'forward':
  33. return (f(a+h) - f(a))/h
  34. elif method == 'backward':
  35. return (f(a) - f(a-h))/h
  36. else:
  37. raise ValueError("Method must be 'central', 'forward' or 'backward'.")
  38.  
  39. answer1 = derivative(np.exp,0,method ='central', h = 0.001)
  40. print("Central", answer1)
  41. answer2 = derivative(np.exp,0,method ='forward', h = 0.001)
  42. print("Forward", answer2)
  43. answer3 = derivative(np.exp,0,method ='backward', h = 0.001)
  44. print("Backward", answer3)
Add Comment
Please, Sign In to add comment