The Derivative as a Limit

~10 mincode completion

Implement central_difference(coeffs, x, h), where coeffs describes a polynomial and the derivative is estimated at x.

is the coefficient of , so [1, 0, 2] means . 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^2

  • x: the point to differentiate at

  • h: the step size

  • Return float: (f(x+h) - f(x-h)) / (2h)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

4 employers weight this skill

4 quant funds. Top match scores 93.

Python
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
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.