Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Math UBC / Numerical Differentiation
- import numpy as np
- import matplotlib.pyplot as plt
- #%matplotlib online
- def derivative(f, a, method, h):
- """
- Compute the difference formula for f'(a) with step h.
- Parameters
- ----------
- f : function
- Vectorized function of one variable
- a : number
- Compute derivative at x = a
- method : string
- Difference formula: 'forward', 'backward' or 'central'
- h : number
- Step size in difference formula
- Returns
- -------
- float
- Difference formula:
- central: f(a+h) - f(a-h))/2h
- forward: f(a+h) - f(a))/h
- backward: f(a) - f(a-h))/h
- """
- if method == 'central':
- return (f(a+h) - f(a-h))/2*h
- elif method == 'forward':
- return (f(a+h) - f(a))/h
- elif method == 'backward':
- return (f(a) - f(a-h))/h
- else:
- raise ValueError("Method must be 'central', 'forward' or 'backward'.")
- answer1 = derivative(np.exp,0,method ='central', h = 0.001)
- print("Central", answer1)
- answer2 = derivative(np.exp,0,method ='forward', h = 0.001)
- print("Forward", answer2)
- answer3 = derivative(np.exp,0,method ='backward', h = 0.001)
- print("Backward", answer3)
Add Comment
Please, Sign In to add comment