{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"checking-a-gradient-numerically","title":"Checking a gradient with finite differences, and the step size that lies","url":"https://addaly.com/learn/maths-you-need/checking-a-gradient-numerically","position":75,"of":76,"minutes":9,"answer":"A two-sided finite difference has truncation error of order h² and rounding error of order ε/h, so the best step is about ε^(1/3).","keyIdea":"A two-sided finite difference has truncation error of order h² and rounding error of order ε/h, so the best step is about ε^(1/3), which in float32 leaves only five correct digits and makes gradient checks meaningful only in float64, where a relative error above 10⁻³ means the gradient is wrong."},"body":{"format":"markdown","text":"## The one test every hand-written gradient needs\n\nModule 3 defined the derivative as the slope between two points as the gap shrinks, and noted that you can compute a usable one with two evaluations and a small number. That is also the way to check a gradient you derived by hand, or a custom backward function, or an autograd system you do not fully trust. Nudge one parameter, see how the loss moves, compare with what the gradient claimed:\n\n```\nnumerical = ( L(θ + h) − L(θ − h) ) / (2h)\n```\n\nThe two-sided form, with `+h` and `−h`, is worth the second evaluation: its error shrinks with `h²` rather than `h`, which the next section shows matters.\n\n## Why h cannot be tiny\n\nThe obvious instinct is to make `h` as small as possible, because the definition of the derivative is a limit. Two errors pull against each other.\n\n**Truncation error.** The slope between two points is not the slope at one point; the curvature of the function contributes an error of order `h²` for the two-sided formula. Smaller `h` reduces it.\n\n**Rounding error.** `L(θ + h) − L(θ − h)` is a subtraction of two nearly equal numbers, and the previous lessons showed what that does: the difference is known only to about machine epsilon `ε` times the size of `L`. Dividing by `2h` amplifies that to `ε/h`. Smaller `h` *increases* it.\n\nThe total error is roughly `h² + ε/h`, smallest when the two terms balance, at `h ≈ ε^(1/3)`:\n\n```\nfloat64: ε = 2.2e-16  →  best h ≈ 6e-6,   best achievable error ≈ 4e-11\nfloat32: ε = 1.2e-7   →  best h ≈ 5e-3,   best achievable error ≈ 2e-5\n```\n\nThe float32 line is the important one. In single precision the best possible numerical derivative agrees with the truth to about five digits, and with `h = 1e-6`, which is what everyone tries first, the rounding term is `0.1`: the check is meaningless. Do gradient checks in float64. Convert the model, run the check, convert back.\n\n## What to compare, and the thresholds\n\nA raw difference between the numerical and analytic gradients means nothing without a scale, so use the relative error:\n\n```\nrel = |analytic − numerical| / ( |analytic| + |numerical| + 1e-12 )\n```\n\nIn float64 with `h ≈ 1e-5`:\n\n```\nrel < 1e-7    correct\nrel ~ 1e-5    probably correct; possibly a kink nearby, see below\nrel ~ 1e-3    something is slightly wrong: a missing factor, a transposed matrix\nrel > 1e-2    the gradient is wrong\n```\n\nCheck a random sample of parameters rather than all of them; a model with a million weights would need two million forward passes, and twenty randomly chosen weights find a systematic error just as well.\n\n## The kinks\n\nA ReLU has no derivative at zero; it has a slope of 0 on one side and 1 on the other. If a parameter nudged by `h` moves some unit across zero, the numerical derivative averages the two slopes and disagrees with the analytic one, which picked a side. This is not a bug. It shows up as a handful of parameters with relative error near `0.5` while all the others are at `10^-8`, and the tell is that the disagreeing ones change when you change `h` or the input. `max`, `abs`, sorting and any thresholding have the same kinks. If *every* parameter disagrees, the gradient is wrong; if a few do and the pattern moves, it is the kinks.\n\n## The code\n\n```python\nimport numpy as np\ndef grad_check(loss, theta, analytic, h=1e-5, n=20, rng=np.random.default_rng(0)):\n    theta = theta.astype(np.float64)\n    for i in rng.choice(theta.size, n, replace=False):\n        e = np.zeros_like(theta); e.flat[i] = h\n        num = (loss(theta + e) - loss(theta - e)) / (2 * h)\n        ana = analytic.flat[i]\n        rel = abs(ana - num) / (abs(ana) + abs(num) + 1e-12)\n        print(i, f\"{ana:.6e} {num:.6e} {rel:.1e}\")\n```\n\nRun it once against a gradient you are sure of, so you know what \"passes\" looks like on your machine, before running it against the one you doubt.\n\n## When the numerical derivative is the derivative\n\nSometimes there is no analytic gradient: a loss that calls a simulator, a black-box metric, a function with a lookup table in it. Finite differences then *are* the gradient, at a cost of two function evaluations per parameter, which is affordable for tens of parameters and hopeless for millions. That is the honest statement of why backpropagation exists: it computes every parameter's gradient for the cost of about two forward passes in total, where finite differences cost two per parameter. Module 3 made that point from the algorithm's side. From the numerical side, the finite-difference gradient is also less accurate, by the `ε^(2/3)` above, so backpropagation is both a million times cheaper and a hundred thousand times more precise. Use finite differences to *check* it, in float64, at the `h` the arithmetic prescribes, and for nothing else."},"check":{"question":"A learner checks a hand-written backward function in float32 with h = 1e-6 and finds relative errors around 0.1 on every parameter. What should they conclude?","options":[{"text":"The backward function is wrong, since 0.1 is far above any acceptable threshold.","correct":false,"tempting":"At h = 1e-6 in float32 the rounding term ε/h is itself about 0.1, so the check cannot distinguish a correct gradient from a wrong one."},{"text":"The network's ReLU kinks are causing every parameter to disagree.","correct":false,"tempting":"Kinks affect a handful of parameters whose set changes with h or input, not all of them uniformly; a uniform 0.1 is the signature of precision, not of kinks."},{"text":"h should be made smaller, since the definition of a derivative takes h to zero.","correct":false,"tempting":"Smaller h makes the rounding term ε/h larger still; the optimum is ε^(1/3), about 5e-3 in float32, and even there only five digits survive."},{"text":"The check is uninformative in float32 at that h; rerun it in float64.","correct":true}]},"prev":{"slug":"random-numbers-and-seeds","title":"Random numbers that are not, and what a seed does and does not fix","url":"https://addaly.com/learn/maths-you-need/random-numbers-and-seeds"},"next":{"slug":"nan-inf-and-the-statistics-of-a-tensor","title":"NaN, Inf, and the five numbers to print about any tensor","url":"https://addaly.com/learn/maths-you-need/nan-inf-and-the-statistics-of-a-tensor"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Checking a gradient with finite differences, and the step size that lies', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/checking-a-gradient-numerically (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Checking a gradient with finite differences, and the step size that lies","courseTitle":"The Maths You Actually Need","module":{"index":8,"slug":"numbers-in-a-machine","title":"Numbers inside a machine"},"answer":null,"keyIdea":"A two-sided finite difference has truncation error of order h² and rounding error of order ε/h, so the best step is about ε^(1/3), which in float32 leaves only five correct digits and makes gradient checks meaningful only in float64, where a relative error above 10⁻³ means the gradient is wrong.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-one-test-every-hand-written-gradient-needs","runs":[{"text":"The one test every hand-written gradient needs"}]},{"t":"p","runs":[{"text":"Module 3 defined the derivative as the slope between two points as the gap shrinks, and noted that you can compute a usable one with two evaluations and a small number. That is also the way to check a gradient you derived by hand, or a custom backward function, or an autograd system you do not fully trust. Nudge one parameter, see how the loss moves, compare with what the gradient claimed:"}]},{"t":"code","lang":"","label":"Text","text":"numerical = ( L(θ + h) − L(θ − h) ) / (2h)"},{"t":"p","runs":[{"text":"The two-sided form, with "},{"text":"+h","code":true},{"text":" and "},{"text":"−h","code":true},{"text":", is worth the second evaluation: its error shrinks with "},{"text":"h²","code":true},{"text":" rather than "},{"text":"h","code":true},{"text":", which the next section shows matters."}]},{"t":"h2","id":"why-h-cannot-be-tiny","runs":[{"text":"Why h cannot be tiny"}]},{"t":"p","runs":[{"text":"The obvious instinct is to make "},{"text":"h","code":true},{"text":" as small as possible, because the definition of the derivative is a limit. Two errors pull against each other."}]},{"t":"p","runs":[{"text":"Truncation error.","b":true},{"text":" The slope between two points is not the slope at one point; the curvature of the function contributes an error of order "},{"text":"h²","code":true},{"text":" for the two-sided formula. Smaller "},{"text":"h","code":true},{"text":" reduces it."}]},{"t":"p","runs":[{"text":"Rounding error.","b":true},{"text":" "},{"text":"L(θ + h) − L(θ − h)","code":true},{"text":" is a subtraction of two nearly equal numbers, and the previous lessons showed what that does: the difference is known only to about machine epsilon "},{"text":"ε","code":true},{"text":" times the size of "},{"text":"L","code":true},{"text":". Dividing by "},{"text":"2h","code":true},{"text":" amplifies that to "},{"text":"ε/h","code":true},{"text":". Smaller "},{"text":"h","code":true},{"text":" "},{"text":"increases","i":true},{"text":" it."}]},{"t":"p","runs":[{"text":"The total error is roughly "},{"text":"h² + ε/h","code":true},{"text":", smallest when the two terms balance, at "},{"text":"h ≈ ε^(1/3)","code":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"float64: ε = 2.2e-16  →  best h ≈ 6e-6,   best achievable error ≈ 4e-11\nfloat32: ε = 1.2e-7   →  best h ≈ 5e-3,   best achievable error ≈ 2e-5"},{"t":"p","runs":[{"text":"The float32 line is the important one. In single precision the best possible numerical derivative agrees with the truth to about five digits, and with "},{"text":"h = 1e-6","code":true},{"text":", which is what everyone tries first, the rounding term is "},{"text":"0.1","code":true},{"text":": the check is meaningless. Do gradient checks in float64. Convert the model, run the check, convert back."}]},{"t":"h2","id":"what-to-compare-and-the-thresholds","runs":[{"text":"What to compare, and the thresholds"}]},{"t":"p","runs":[{"text":"A raw difference between the numerical and analytic gradients means nothing without a scale, so use the relative error:"}]},{"t":"code","lang":"","label":"Text","text":"rel = |analytic − numerical| / ( |analytic| + |numerical| + 1e-12 )"},{"t":"p","runs":[{"text":"In float64 with "},{"text":"h ≈ 1e-5","code":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"rel < 1e-7    correct\nrel ~ 1e-5    probably correct; possibly a kink nearby, see below\nrel ~ 1e-3    something is slightly wrong: a missing factor, a transposed matrix\nrel > 1e-2    the gradient is wrong"},{"t":"p","runs":[{"text":"Check a random sample of parameters rather than all of them; a model with a million weights would need two million forward passes, and twenty randomly chosen weights find a systematic error just as well."}]},{"t":"h2","id":"the-kinks","runs":[{"text":"The kinks"}]},{"t":"p","runs":[{"text":"A ReLU has no derivative at zero; it has a slope of 0 on one side and 1 on the other. If a parameter nudged by "},{"text":"h","code":true},{"text":" moves some unit across zero, the numerical derivative averages the two slopes and disagrees with the analytic one, which picked a side. This is not a bug. It shows up as a handful of parameters with relative error near "},{"text":"0.5","code":true},{"text":" while all the others are at "},{"text":"10^-8","code":true},{"text":", and the tell is that the disagreeing ones change when you change "},{"text":"h","code":true},{"text":" or the input. "},{"text":"max","code":true},{"text":", "},{"text":"abs","code":true},{"text":", sorting and any thresholding have the same kinks. If "},{"text":"every","i":true},{"text":" parameter disagrees, the gradient is wrong; if a few do and the pattern moves, it is the kinks."}]},{"t":"h2","id":"the-code","runs":[{"text":"The code"}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\ndef grad_check(loss, theta, analytic, h=1e-5, n=20, rng=np.random.default_rng(0)):\n    theta = theta.astype(np.float64)\n    for i in rng.choice(theta.size, n, replace=False):\n        e = np.zeros_like(theta); e.flat[i] = h\n        num = (loss(theta + e) - loss(theta - e)) / (2 * h)\n        ana = analytic.flat[i]\n        rel = abs(ana - num) / (abs(ana) + abs(num) + 1e-12)\n        print(i, f\"{ana:.6e} {num:.6e} {rel:.1e}\")"},{"t":"p","runs":[{"text":"Run it once against a gradient you are sure of, so you know what “passes” looks like on your machine, before running it against the one you doubt."}]},{"t":"h2","id":"when-the-numerical-derivative-is-the-derivative","runs":[{"text":"When the numerical derivative is the derivative"}]},{"t":"p","runs":[{"text":"Sometimes there is no analytic gradient: a loss that calls a simulator, a black-box metric, a function with a lookup table in it. Finite differences then "},{"text":"are","i":true},{"text":" the gradient, at a cost of two function evaluations per parameter, which is affordable for tens of parameters and hopeless for millions. That is the honest statement of why backpropagation exists: it computes every parameter’s gradient for the cost of about two forward passes in total, where finite differences cost two per parameter. Module 3 made that point from the algorithm’s side. From the numerical side, the finite-difference gradient is also less accurate, by the "},{"text":"ε^(2/3)","code":true},{"text":" above, so backpropagation is both a million times cheaper and a hundred thousand times more precise. Use finite differences to "},{"text":"check","i":true},{"text":" it, in float64, at the "},{"text":"h","code":true},{"text":" the arithmetic prescribes, and for nothing else."}]}],"check":{"question":[{"text":"A learner checks a hand-written backward function in float32 with h = 1e-6 and finds relative errors around 0.1 on every parameter. What should they conclude?"}],"options":[{"text":[{"text":"The backward function is wrong, since 0.1 is far above any acceptable threshold."}],"correct":false,"tempting":[{"text":"At h = 1e-6 in float32 the rounding term ε/h is itself about 0.1, so the check cannot distinguish a correct gradient from a wrong one."}]},{"text":[{"text":"The network’s ReLU kinks are causing every parameter to disagree."}],"correct":false,"tempting":[{"text":"Kinks affect a handful of parameters whose set changes with h or input, not all of them uniformly; a uniform 0.1 is the signature of precision, not of kinks."}]},{"text":[{"text":"h should be made smaller, since the definition of a derivative takes h to zero."}],"correct":false,"tempting":[{"text":"Smaller h makes the rounding term ε/h larger still; the optimum is ε^(1/3), about 5e-3 in float32, and even there only five digits survive."}]},{"text":[{"text":"The check is uninformative in float32 at that h; rerun it in float64."}],"correct":true,"tempting":null}],"order":[2,3,0,1],"why":null},"prev":{"slug":"random-numbers-and-seeds","title":"Random numbers that are not, and what a seed does and does not fix","minutes":9},"next":{"slug":"nan-inf-and-the-statistics-of-a-tensor","title":"NaN, Inf, and the five numbers to print about any tensor","minutes":9}}}