Compute the Hessian matrix (matrix of second-order partial derivatives) of a given multivariable function at a specified point using numerical differentiation.
def compute_hessian(f, point: list[float], h: float = 1e-5) -> list[list[float]]:
n = len(point)
hessian = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
# f(x + ei*h + ej*h)
pp = point[:]
pp[i] += h
pp[j] += h
f_pp = f(pp)
# f(x + ei*h - ej*h)
pm = point[:]
pm[i] += h
pm[j] -= h
f_pm = f(pm)
# f(x - ei*h + ej*h)
mp = point[:]
mp[i] -= h
mp[j] += h
f_mp = f(mp)
# f(x - ei*h - ej*h)
mm = point[:]
mm[i] -= h
mm[j] -= h
f_mm = f(mm)
hessian[i][j] = round((f_pp - f_pm - f_mp + f_mm) / (4 * h * h), 4)
return hessian(f(x+h_i+h_j) - f(x+h_i-h_j) - f(x-h_i+h_j) + f(x-h_i-h_j)) / (4h^2).