The Derivative as a Limit
Implement central_difference(coeffs, x, h), where coeffs describes a polynomial and the derivative is estimated at x.
is the coefficient of xi, so [1, 0, 2] means 1+2x2. Evaluate with np.polyval(coeffs[::-1], x), which expects the highest power first.
Examples
x squared has slope 2x, which is 6 at x = 3
- Input
- central_difference([0, 0, 1], 3, 0.00001)
- Output
- 6
A straight line has the same slope everywhere
- Input
- central_difference([4, 2], 100, 0.00001)
- Output
- 2
A constant does not change, so its derivative is zero
- Input
- central_difference([7], 2, 0.00001)
- Output
- 0
Hints
Hint 1
Convert the input with before doing elementwise work.
Hint 2
A common slip here: divides by h instead of 2h.
Requirements
coeffs: coefficients low power first, so [1, 0, 2] is 1 + 2x^2x: the point to differentiate ath: the step sizeReturn float: (f(x+h) - f(x-h)) / (2h)
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
4 employers weight this skill
4 quant funds. Top match scores 93.
import numpy as np
def central_difference(coeffs, x, h):
"""
Numerical derivative of a polynomial by central difference.
Args:
coeffs: coefficients low power first, so [1, 0, 2] is 1 + 2x^2
x: the point to differentiate at
h: the step size
Returns:
float: (f(x+h) - f(x-h)) / (2h)
"""
# YOUR CODE HERE
pass