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 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 · Данные: , .
Аналитически .
Ожидаемые числа
| Quantity | Value | Tolerance |
|---|---|---|
Самопроверка в ноутбуке
Не влияет на 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")