Neural Mastery
← Practice
Central Finite Difference Gradient Approximationmedium

Central Finite Difference Gradient Approximation

medium Math for ML 10-15 min

NumPy allowed · plain Python earns 10 bonus points

Gradient descent step 1/4

Loss moves downhill

The update rule changes the parameters on each step.
Open lesson →
01parameters
02prediction
03loss
04gradient
θ = 4.000loss = 16.000∂L/∂θ = 8.000

θ ← θ − 0.14 · ∂L/∂θ

Approximate the multivariable gradient vector using second-order accurate central finite differences.

Task

Implement finite_difference_gradient(f_center, f_plus, f_minus, h=0.0001): given perturbed function values f_plus (evaluated at x + h*e_i) and f_minus (evaluated at x - h*e_i), compute g_i = (f_plus[i] - f_minus[i]) / (2 * h). Return gradient vector rounded to 4 decimals.

Function Signature

finite_difference_gradient(f_center: float, f_plus: list[float], f_minus: list[float], h: float = 0.0001) -> list[float]

Examples

Example 1: Quadratic 1D Finite Difference
Input: f_center = 4 f_plus = [4.0401] f_minus = [3.9601] h = 0.01
Output: [4]
Explanation: Central difference of x^2 at x=2.
Example 2: 2D Multivariable Gradients
Input: f_center = 5 f_plus = [5.02, 5.06] f_minus = [4.98, 4.94] h = 0.01
Output: [2, 6]
Explanation: 2D gradient central differences.

Constraints

  • f_plus and f_minus have matching length d.
  • h > 0.
Python3Saved ✓
def finite_difference_gradient(f_center: float, f_plus: list[float], f_minus: list[float], h: float = 0.0001) -> list[float]:
"""Compute numerical gradient using central differences g_i = (f(x0 + h e_i) - f(x0 - h e_i)) / (2 * h).
Return gradient vector rounded to 4 decimals."""
# Your implementation here
pass

Case 1: Quadratic 1D Finite Difference
Input: f_center = 4 f_plus = [4.0401] f_minus = [3.9601] h = 0.01
Expected: [4]
Case 2: 2D Multivariable Gradients
Input: f_center = 5 f_plus = [5.02, 5.06] f_minus = [4.98, 4.94] h = 0.01
Expected: [2, 6]