v9.1.1
Menu

Numerical Gradient

easyFREECalculus & OptimizationCalculus, Numerical MethodsCV: Mathematical Foundations

Implement a function to compute the numerical gradient of a given function at a specific point using finite differences. This task is essential in calculus and optimization when analytical gradients are not available.

The concept of gradients is crucial in understanding the rate of change of a function. In mathematics, the derivative of a function ff at a point xx represents the rate of change of the function with respect to xx. The derivative can be approximated using the central difference formula, which is a fundamental concept in numerical analysis.

To approximate the derivative, we can follow these steps:

  1. Evaluate the function at x+hx + h and x−hx - h.
  2. Calculate the difference between these two function values.
  3. Divide the result by 2h2h to obtain the approximate derivative.
f′(x)≈f(x+h)−f(x−h)2hf'(x) \approx \frac{f(x + h) - f(x - h)}{2h}

This technique is widely used in machine learning for training models when analytical gradients are unavailable.

Example

Input
numerical_gradient(lambda x: x**2, 3.0)
Output
6.0
Reasoning
  • Inputs: f is the function being differentiated, here f(x)=x2f(x) = x^2; x =3.0= 3.0 is the point where we want the slope; h =10−5= 10^{-5} is the tiny step taken to each side of that point.
  • Probe both sides: f(3.00001)=9.0000600001f(3.00001) = 9.0000600001 and f(2.99999)=8.9999400001f(2.99999) = 8.9999400001. The two values straddle f(3)=9f(3) = 9 almost symmetrically.
  • Central difference: the rise is 9.0000600001−8.9999400001=0.000129.0000600001 - 8.9999400001 = 0.00012 over a run of 2h=0.000022h = 0.00002, so 0.000120.00002≈6.00000000004\frac{0.00012}{0.00002} \approx 6.00000000004.
  • Output: rounded to 4 decimal places this is 6.0, matching the exact derivative 2x=62x = 6 at x=3x = 3. The trailing 4×10−114 \times 10^{-11} is floating-point noise that rounding removes.
  • Notice: for a parabola the h2h^2 terms cancel in the central difference, so the estimate is exact up to round-off. For x3x^3 at x=2x = 2 a small h2h^2 error (about 10−1010^{-10}) remains, and rounding still gives 12.012.0.

Constraints

  • Use h = 1e-5 for the finite difference
  • The function f takes a single float and returns a float
  • Return the gradient rounded to 4 decimal places

Learn this in

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.