Skip to content
BIASED
Back to topic

Optional

Gradient vs finite differences

Match analytic ∇f to central differences on R^3; tol 1e-5.

Version
v1
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Math · Градиент vs конечные разности / Gradient vs finite differences

Activity version: 1 · Seed: 0 · Данные: f(x)=12∥x∥22+sin⁡(x0)f(x)=\tfrac12\|x\|_2^2 + \sin(x_0), x∈R3x\in\mathbb R^3.

Аналитически ∇f(x)=x+(cos⁡(x0),0,0)\nabla f(x)=x+(\cos(x_0),0,0).

Ожидаемые числа
Quantity Value Tolerance
∥∇f−∇f^∥∞\|\nabla f - \widehat{\nabla f}\|_\infty <10−5<10^{-5}
Самопроверка в ноутбуке

Не влияет на mastery.

import numpy as np
 
rng = np.random.default_rng(0)
x = rng.normal(size=3)
 
def f(z):
    return 0.5 * np.dot(z, z) + np.sin(z[0])
 
def grad(z):
    g = z.copy()
    g[0] += np.cos(z[0])
    return g
 
eps = 1e-6
fd = np.zeros_like(x)
for i in range(3):
    e = np.zeros(3); e[i] = 1.0
    fd[i] = (f(x + eps * e) - f(x - eps * e)) / (2 * eps)
 
g = grad(x)
err = np.max(np.abs(g - fd))
print("grad", g, "fd", fd, "err", err)
assert err < 1e-5
print("OK: finite-diff gradient check")
Самопроверка в ноутбуке
  • ∥∇f−∇f^∥∞<10−5\|\nabla f-\widehat{\nabla f}\|_\infty < 10^{-5}