All problems
Numerical Gradient of 2D Function
Problem
Compute the numerical gradient of f(x, y) = x^3 + a * x * y^2 at (x, y) using central differences with h = 1e-6.
Return [df/dx, df/dy] where each partial uses the symmetric difference quotient. The analytic gradient is [3*x^2 + a*y^2, 2*a*x*y].
Hint
Perturb one variable at a time and keep the step symmetric around the point.
Test cases
case 1
in: [1,2,1]
expected: [13,4]
case 2
in: [0,-2,3]
expected: [12,0]
case 3
in: [2,0,5]
expected: [50,0]
case 4
in: [-1,1,2]
expected: [-1,-4]
Starter codePython
def numerical_gradient_2d(a, x, y, h=1e-6):
# Return [df_dx, df_dy]
# Your code here
pass4 test cases · run your code against them in the editor