Type at least 2 letters. Enter opens the first result, Esc closes.

    ML for Science · Lesson 12 · Stochastic and generative models

    Stochastic differential equations, Itô calculus and the Fokker–Planck equation

    Advanced 110 min 5 interactive figures 5 videos Colab notebook

    Before this lesson: order of convergence and time stepping (lesson 02); Taylor expansion to second order (calculus 03); the Gaussian distribution (probability 05); Monte Carlo estimates and their error bars (probability 14). Langevin dynamics and Markov chains (probability 15) help but are not required. Time: about 110 minutes, plus the notebook.


    Why this matters #

    • Diffusion models are SDEs. The forward process of a diffusion model adds noise along an OU-type SDE. The sampler integrates a reverse-time SDE or a deterministic ODE with the same marginals (lesson 13). Both come from the Fokker–Planck equation of this lesson.
    • One-shot training needs the exact solution. Training a diffusion model draws a noisy sample at any time tt in one step, with no simulation. That is possible because the OU process has a Gaussian solution, which we derive with Itô's lemma.
    • Sampler cost is a question of weak order. A generative sampler must get the distribution right, not one particular noise path. The weak order of the solver tells you how fast the error falls with the number of steps.
    • Climate models use stochastic terms. Hasselmann's stochastic climate model is an OU process, and ensemble prediction systems perturb their physics with random patterns that evolve as discretised OU processes.
    • Langevin samplers draw from a density π\pi by simulating an SDE whose stationary density is π\pi. The zero-flux condition of the Fokker–Planck equation proves that this works.

    1. Predict first #

    2. The picture #

    Brownian motion: kicks of size h\sqrt h #

    Brownian motion (also called the Wiener process) WtW_t is the simplest random path. It starts at W0=0W_0 = 0, it is continuous, and its increments are independent Gaussians:

    Wt+h−Wt∼N(0,h).W_{t+h} - W_t \sim \mathcal N(0, h).

    So a step of length hh moves the path by a random amount with standard deviation h\sqrt h. For small hh, h\sqrt h is much larger than hh: for h=0.01h = 0.01, h=0.1\sqrt h = 0.1. This makes the path very rough. It is continuous, but it has no slope anywhere.

    Cut [0,T][0, T] into NN steps of size h=T/Nh = T/N and add up the increments in two ways:

    • the total variation ∑k∣ΔWk∣\sum_k |\Delta W_k| (the length of the path, seen at resolution hh). Each term has mean 2h/π\sqrt{2h/\pi}, so the sum has mean 2NT/π\sqrt{2NT/\pi}. It grows without limit as N→∞N \to \infty;
    • the quadratic variation ∑k(ΔWk)2\sum_k (\Delta W_k)^2. Each term has mean hh, so the sum has mean TT. Its variance is N⋅2h2=2T2/NN \cdot 2h^2 = 2T^2/N, which goes to 0.

    So the sum of squared increments does not vanish: it converges to exactly TT. In a smooth function the squares of small changes are O(h2)O(h^2) and disappear. For Brownian motion, (ΔW)2(\Delta W)^2 is of order hh, the same order as dtdt. In the limit we write

    (dW)2=dt.(dW)^2 = dt .

    This one rule produces the extra term of Itô's lemma below.

    Interactive figure: loading…

    Move the slider to refine the grid. All grids use the same Brownian path (the coarse increments are sums of fine ones). Top: the path on the current grid. Bottom, on log–log axes: the total variation grows like N\sqrt N, while the quadratic variation settles at T=1T = 1; grey dashed lines are the expected values, the yellow dots mark the current NN. Press New path a few times: the quadratic variation is close to 1 on every path when NN is large.

    An SDE is a limit of a simple recipe #

    An SDE in one dimension is written

    dX=a(X,t) dt+b(X,t) dW.dX = a(X, t)\,dt + b(X, t)\,dW .

    The function aa is the drift: it moves the mean. The function bb is the diffusion coefficient: it sets the size of the random kicks. The SDE is defined as the limit of this update, the Euler–Maruyama (EM) method:

    Xn+1=Xn+a(Xn,tn) h+b(Xn,tn) ΔWn,ΔWn∼N(0,h).X_{n+1} = X_n + a(X_n, t_n)\,h + b(X_n, t_n)\,\Delta W_n, \qquad \Delta W_n \sim \mathcal N(0, h).

    Each step adds the mean change aha h and the variance b2hb^2 h. The coefficients are evaluated at the left point (Xn,tn)(X_n, t_n), before the noise of the step is known. This choice defines the Itô interpretation of the SDE. With b=0b = 0 it is forward Euler for the ODE x′=a(x,t)x' = a(x, t) (lesson 02).

    The chain rule gets an extra term #

    Take geometric Brownian motion (GBM), dX=μX dt+σX dWdX = \mu X\,dt + \sigma X\,dW: the noise is proportional to XX. If the ordinary chain rule held, log⁡X\log X would grow at rate μ\mu. It does not. Section 3 shows that log⁡X\log X grows at rate μ−σ2/2\mu - \sigma^2/2. The mean EXt=x0eμtE X_t = x_0 e^{\mu t} still grows at rate μ\mu, but the median (the typical path) grows only at rate μ−σ2/2\mu - \sigma^2/2. A few large paths pull the mean up.

    Interactive figure: loading…

    Increase the volatility σ\sigma and watch the two lines separate. Grey: 40 of 1000 exact GBM paths (log scale). Orange, dashed: the mean eμte^{\mu t}, which is also what the ordinary chain rule predicts for the typical path. Blue: the true median e(μ−σ2/2)te^{(\mu - \sigma^2/2)t}. Dots are the sample mean and median of the 1000 paths. Bottom: the histogram of log⁡XT\log X_T is Gaussian around (μ−σ2/2)T(\mu - \sigma^2/2)T. Try μ=σ2/2\mu = \sigma^2/2: the mean grows, but half of the paths end below 1.

    From paths to a density #

    You can follow single paths, or you can follow the density p(x,t)p(x, t) of a very large cloud of paths. The density is not random. It obeys a partial differential equation, the Fokker–Planck equation: the drift transports probability (like wind carries smoke), and the noise spreads it (like heat diffusion). An ensemble forecast with many members is a Monte Carlo approximation of this equation.

    The simplest example with both effects is the Ornstein–Uhlenbeck process dX=−θX dt+σ dWdX = -\theta X\,dt + \sigma\,dW. The drift −θX-\theta X pulls XX back toward 0 at rate θ\theta; the noise pushes it away. The two balance in a stationary Gaussian with variance σ2/(2θ)\sigma^2/(2\theta).

    Interactive figure: loading…

    Press Play, or move the time tt. Top: 25 of 2000 OU paths; the dashed blue line is the mean x0e−θtx_0 e^{-\theta t}. Bottom: the histogram of all 2000 paths at time tt, the Fokker–Planck solution N(x0e−θt,σ22θ(1−e−2θt))\mathcal N\big(x_0e^{-\theta t}, \tfrac{\sigma^2}{2\theta}(1 - e^{-2\theta t})\big) and the grey dashed stationary density. Each path is random; the histogram follows one deterministic curve. Increase θ\theta: the process forgets x0x_0 faster, and the stationary density gets narrower.

    Quick check

    A Brownian increment over a step hh is ΔW∼N(0,h)\Delta W \sim \mathcal N(0, h). What is E[(ΔW)2]E[(\Delta W)^2]?

    3. Definitions and main results #

    Brownian motion and the Itô integral #

    Brownian motion WtW_t: W0=0W_0 = 0; increments over disjoint intervals are independent; Wt−Ws∼N(0,t−s)W_t - W_s \sim \mathcal N(0, t - s) for s<ts < t; paths are continuous. It follows that Cov⁡(Ws,Wt)=min⁡(s,t)\operatorname{Cov}(W_s, W_t) = \min(s, t).

    A process gtg_t is non-anticipating if gtg_t depends only on the path up to time tt, not on the future. For such gg, the Itô integral is the limit of left-point sums:

    ∫0Tgt dWt=lim⁡h→0∑kgtk (Wtk+1−Wtk).\int_0^T g_t\,dW_t = \lim_{h \to 0} \sum_k g_{t_k}\,\big(W_{t_{k+1}} - W_{t_k}\big).

    Because gtkg_{t_k} is independent of the next increment, two properties follow:

    • mean zero: E∫0Tg dW=0E\int_0^T g\,dW = 0;
    • Itô isometry: E[(∫0Tg dW)2]=∫0TE[gt2] dtE\Big[\big(\int_0^T g\,dW\big)^2\Big] = \int_0^T E[g_t^2]\,dt.

    An Itô SDE dX=a(X,t) dt+b(X,t) dWdX = a(X, t)\,dt + b(X, t)\,dW is shorthand for the integral equation Xt=X0+∫0ta ds+∫0tb dWX_t = X_0 + \int_0^t a\,ds + \int_0^t b\,dW.

    Theorem 1 (Itô's lemma) #

    Let XX solve dX=a dt+b dWdX = a\,dt + b\,dW, and let f(x,t)f(x, t) be once differentiable in tt and twice in xx. Then Yt=f(Xt,t)Y_t = f(X_t, t) solves

    dY=(ft+a fx+12 b2fxx) dt+b fx dW.dY = \Big(f_t + a\,f_x + \tfrac12\,b^2 f_{xx}\Big)\,dt + b\,f_x\,dW .

    Why this is true (intuition). Expand ff to second order. In ordinary calculus the second-order term 12fxx(dX)2\tfrac12 f_{xx}(dX)^2 is O(h2)O(h^2) and disappears. Here (dX)2(dX)^2 contains b2(dW)2=b2 dtb^2(dW)^2 = b^2\,dt, which is first order, so half of it survives.

    Proof sketch
    1. Taylor-expand ff over one step: Δf=ft h+fx ΔX+12fxx (ΔX)2+…\Delta f = f_t\,h + f_x\,\Delta X + \tfrac12 f_{xx}\,(\Delta X)^2 + \dots
    2. Insert ΔX=ah+b ΔW\Delta X = a h + b\,\Delta W: (ΔX)2=a2h2+2ab h ΔW+b2(ΔW)2(\Delta X)^2 = a^2 h^2 + 2ab\,h\,\Delta W + b^2(\Delta W)^2.
    3. The first two terms are O(h2)O(h^2) and O(h3/2)O(h^{3/2}) per step. Over N=T/hN = T/h steps they sum to O(h)O(h) and O(h1/2)O(h^{1/2}), which vanish as h→0h \to 0.
    4. The last term: (ΔW)2(\Delta W)^2 has mean hh and variance 2h22h^2. Summed over NN steps with a bounded weight ck=12fxxb2c_k = \tfrac12 f_{xx}b^2, the sum ∑ck(ΔWk)2\sum c_k(\Delta W_k)^2 has mean ∑ckh→∫c dt\sum c_k h \to \int c\,dt and a variance of order Nh2=Th→0N h^2 = T h \to 0. So in the limit (dW)2(dW)^2 can be replaced by dtdt.
    5. Third-order terms such as (ΔW)3(\Delta W)^3 are O(h3/2)O(h^{3/2}) per step and sum to O(h1/2)→0O(h^{1/2}) \to 0.
    6. Collect the dtdt terms and the dWdW term. ■\blacksquare

    The rules to remember are dt2=0dt^2 = 0, dt dW=0dt\,dW = 0, (dW)2=dt(dW)^2 = dt. With b=0b = 0 the lemma is the ordinary chain rule. The new term 12b2fxx\tfrac12 b^2 f_{xx} is the Itô correction. For a convex ff it is positive: noise pushes f(X)f(X) up on average (this is Jensen's inequality, Ef(X)≥f(EX)E f(X) \ge f(E X)).

    Example 1. f=x2f = x^2 and X=WX = W (a=0a = 0, b=1b = 1): fx=2xf_x = 2x, fxx=2f_{xx} = 2, so d(W2)=2W dW+dtd(W^2) = 2W\,dW + dt. Taking expectations, ddtE[Wt2]=1\frac{d}{dt}E[W_t^2] = 1 and E[Wt2]=tE[W_t^2] = t.

    Example 2: geometric Brownian motion. dX=μX dt+σX dWdX = \mu X\,dt + \sigma X\,dW. Take f=log⁡xf = \log x, so fx=1/xf_x = 1/x, fxx=−1/x2f_{xx} = -1/x^2:

    drift: ft+afx+12b2fxx=0+μX⋅1X+12σ2X2⋅(−1X2)=μ−12σ2,diffusion: bfx=σX⋅1X=σ,so dlog⁡X=(μ−12σ2) dt+σ dW.\begin{aligned} \text{drift: } & f_t + a f_x + \tfrac12 b^2 f_{xx} = 0 + \mu X\cdot\frac1X + \frac12\sigma^2X^2\cdot\Big(-\frac1{X^2}\Big) = \mu - \tfrac12\sigma^2,\\ \text{diffusion: } & b f_x = \sigma X\cdot\frac1X = \sigma,\\ \text{so } & d\log X = \big(\mu - \tfrac12\sigma^2\big)\,dt + \sigma\,dW . \end{aligned}

    The right side has constant coefficients, so we can integrate it directly:

    Xt=x0exp⁡ ⁣((μ−12σ2)t+σWt).X_t = x_0 \exp\!\Big(\big(\mu - \tfrac12\sigma^2\big)t + \sigma W_t\Big).

    The median of XtX_t is x0e(μ−σ2/2)tx_0e^{(\mu - \sigma^2/2)t} (the median of WtW_t is 0). The mean is x0eμtx_0e^{\mu t}, because E eσWt=eσ2t/2E\,e^{\sigma W_t} = e^{\sigma^2 t/2} (the moment generating function of N(0,t)\mathcal N(0, t)).

    Quick check

    By Itô's lemma, what is d(Wt2)d(W_t^2)?

    Theorem 2 (the Ornstein–Uhlenbeck process) #

    The OU process dX=−θX dt+σ dWdX = -\theta X\,dt + \sigma\,dW with mean-reversion rate θ>0\theta > 0, noise level σ>0\sigma > 0 and X0=x0X_0 = x_0 has the solution

    Xt=e−θtx0+σ∫0te−θ(t−s) dWs∼N(e−θtx0, σ22θ(1−e−2θt)).\begin{aligned} X_t &= e^{-\theta t}x_0 + \sigma\int_0^t e^{-\theta(t-s)}\,dW_s\\ &\sim \mathcal N\Big(e^{-\theta t}x_0,\ \frac{\sigma^2}{2\theta}\big(1 - e^{-2\theta t}\big)\Big). \end{aligned}
    Proof
    1. Use an integrating factor, as for the linear ODE x′=−θxx' = -\theta x: let Y=eθtXY = e^{\theta t}X, that is f(x,t)=eθtxf(x, t) = e^{\theta t}x with ft=θeθtxf_t = \theta e^{\theta t}x, fx=eθtf_x = e^{\theta t}, fxx=0f_{xx} = 0.
    2. Itô's lemma: dY=(θeθtX−θXeθt)dt+σeθt dW=σeθt dWdY = \big(\theta e^{\theta t}X - \theta X e^{\theta t}\big)dt + \sigma e^{\theta t}\,dW = \sigma e^{\theta t}\,dW. There is no correction term, because ff is linear in xx.
    3. Integrate from 0 to tt: eθtXt−x0=σ∫0teθs dWse^{\theta t}X_t - x_0 = \sigma\int_0^t e^{\theta s}\,dW_s. Multiply by e−θte^{-\theta t}.
    4. The integral of a deterministic function against dWdW is a limit of sums of independent Gaussians, so it is Gaussian, with mean 0.
    5. Its variance, by the Itô isometry, is σ2∫0te−2θ(t−s) ds=σ22θ(1−e−2θt)\sigma^2\int_0^t e^{-2\theta(t-s)}\,ds = \frac{\sigma^2}{2\theta}(1 - e^{-2\theta t}). ■\blacksquare

    As t→∞t \to \infty the mean goes to 0 and the variance to σ2/(2θ)\sigma^2/(2\theta): the stationary distribution is N(0,σ2/(2θ))\mathcal N\big(0, \sigma^2/(2\theta)\big). The time scale of the memory is 1/θ1/\theta.

    The same argument over one step of length Δ\Delta gives the exact transition

    Xt+Δ∣Xt∼N(e−θΔXt, σ22θ(1−e−2θΔ)).X_{t+\Delta} \mid X_t \sim \mathcal N\Big(e^{-\theta\Delta}X_t,\ \frac{\sigma^2}{2\theta}\big(1 - e^{-2\theta\Delta}\big)\Big).

    So an OU process sampled every Δ\Delta is an AR(1) process (time series 05) with coefficient e−θΔe^{-\theta\Delta}, and this sampling has no step-size error. With a mean level μ\mu, dX=θ(μ−X) dt+σ dWdX = \theta(\mu - X)\,dt + \sigma\,dW, replace xx by x−μx - \mu everywhere.

    Quick check

    An OU process has θ=2\theta = 2 and σ=1\sigma = 1. What is its stationary variance?

    Theorem 3 (Fokker–Planck equation) #

    Let XX solve dX=a(x,t) dt+b(x,t) dWdX = a(x, t)\,dt + b(x, t)\,dW with smooth aa and bb, and let XtX_t have a smooth density p(x,t)p(x, t). Then

    ∂tp=−∂x(a p)+12 ∂xx(b2p).\partial_t p = -\partial_x\big(a\,p\big) + \tfrac12\,\partial_{xx}\big(b^2 p\big).

    The first term is advection (the drift carries probability), the second is diffusion (the noise spreads it). Note that b2b^2 stays inside the second derivative.

    Proof (from Itô's lemma)
    1. Take any smooth test function φ(x)\varphi(x) that is zero outside a bounded set. By Itô's lemma, dφ(X)=(aφ′+12b2φ′′)dt+bφ′ dWd\varphi(X) = \big(a\varphi' + \tfrac12 b^2\varphi''\big)dt + b\varphi'\,dW.
    2. Take expectations. The dWdW term has mean zero: ddtEφ(Xt)=E[aφ′+12b2φ′′]\frac{d}{dt}E\varphi(X_t) = E\big[a\varphi' + \tfrac12 b^2\varphi''\big].
    3. Write both sides as integrals against the density: ∫φ ∂tp dx=∫(aφ′+12b2φ′′) p dx\int \varphi\,\partial_t p\,dx = \int \big(a\varphi' + \tfrac12 b^2\varphi''\big)\,p\,dx.
    4. Integrate by parts, once for the φ′\varphi' term and twice for the φ′′\varphi'' term. The boundary terms vanish because φ\varphi does: ∫φ ∂tp dx=∫φ [−∂x(ap)+12∂xx(b2p)] dx\int \varphi\,\partial_t p\,dx = \int \varphi\,\big[-\partial_x(a p) + \tfrac12\partial_{xx}(b^2 p)\big]\,dx.
    5. This holds for every test function φ\varphi, so the two functions in brackets are equal. ■\blacksquare

    The operator Aφ=aφ′+12b2φ′′\mathcal A\varphi = a\varphi' + \tfrac12 b^2\varphi'' in step 2 is the generator of the SDE. The Fokker–Planck operator is its adjoint: integration by parts moves the derivatives from φ\varphi to pp. This is the same "move the derivative to the other factor" idea as in the adjoint methods of lesson 03.

    Fokker–Planck in dd dimensions

    For dX=a(X,t) dt+B(X,t) dWdX = a(X, t)\,dt + B(X, t)\,dW with X∈RdX \in \R^d, W∈RmW \in \R^m and BB a d×md \times m matrix, let D=BB⊤D = BB^\top. Then

    ∂tp=−∇⋅(a p)+12∑i,j∂i∂j(Dij p).\partial_t p = -\nabla\cdot(a\,p) + \tfrac12\sum_{i,j}\partial_i\partial_j\big(D_{ij}\,p\big).

    For the diffusion-model case B=g(t) IB = g(t)\,I (the same noise in every direction, independent of xx) this is ∂tp=−∇⋅(a p)+12g2Δp\partial_t p = -\nabla\cdot(a\,p) + \tfrac12 g^2\Delta p, where Δ\Delta is the Laplacian. Lesson 13 starts from this form.

    Stationary densities and probability flux #

    Write the 1D equation as a conservation law, ∂tp=−∂xJ\partial_t p = -\partial_x J, with the probability flux

    J=a p−12 ∂x(b2p).J = a\,p - \tfrac12\,\partial_x\big(b^2 p\big).

    J(x)J(x) is the rate at which probability crosses the point xx from left to right. A stationary density has ∂xJ=0\partial_x J = 0, so JJ is a constant. On the whole real line, with pp and JJ decaying in the tails, that constant is 0. This is the zero-flux condition:

    a p=12 (b2p)′.a\,p = \tfrac12\,\big(b^2 p\big)' .
    • OU (a=−θxa = -\theta x, b=σb = \sigma): −θx p=σ22p′-\theta x\,p = \tfrac{\sigma^2}{2}p'. So p′/p=−2θx/σ2p'/p = -2\theta x/\sigma^2 and p∝e−θx2/σ2p \propto e^{-\theta x^2/\sigma^2}, which is N(0,σ2/(2θ))\mathcal N\big(0, \sigma^2/(2\theta)\big), as in Theorem 2.
    • Overdamped Langevin dynamics dX=−U′(X) dt+2 dWdX = -U'(X)\,dt + \sqrt2\,dW with a potential UU: zero flux gives −U′p=p′-U'p = p', so p∝e−Up \propto e^{-U}, the Gibbs density. With U=−log⁡πU = -\log \pi the SDE dX=(log⁡π)′(X) dt+2 dWdX = (\log\pi)'(X)\,dt + \sqrt2\,dW has π\pi as its stationary density. It needs only the derivative of log⁡π\log \pi, not the normalising constant of π\pi. This derivative is the score, the central object of lesson 13.
    • With multiplicative noise (bb depends on xx), solve the zero-flux equation for q=b2pq = b^2p: q′=(2a/b2) qq' = (2a/b^2)\,q, a first-order linear ODE.
    Interactive figure: loading…

    Press Play and watch the fluxes. The density solves the Fokker–Planck equation of dX=−U′(X) dt+σ dWdX = -U'(X)\,dt + \sigma\,dW with reflecting walls at ±3\pm 3. Top: the density and the grey dashed Gibbs density ∝e−2U/σ2\propto e^{-2U/\sigma^2}. Bottom: the drift flux a pa\,p, the diffusion flux −σ22p′-\tfrac{\sigma^2}{2}p' and their sum, the total flux JJ (positive means "to the right"). At stationarity the two fluxes are mirror images and J=0J = 0. In the double well, notice the long final phase: a small flux over the barrier at x=0x = 0 slowly fills the left well.

    Quick check

    What is the stationary density of dX=−U′(X) dt+2 dWdX = -U'(X)\,dt + \sqrt2\,dW?

    Itô or Stratonovich?

    The Stratonovich integral ∫g∘dW\int g \circ dW evaluates gg at the midpoint of each step instead of the left point. It obeys the ordinary chain rule, but its mean is not zero in general. Example: ∫0TW dW=12(WT2−T)\int_0^T W\,dW = \tfrac12(W_T^2 - T) (Itô) while ∫0TW∘dW=12WT2\int_0^T W\circ dW = \tfrac12W_T^2 (Stratonovich).

    A Stratonovich SDE dX=a dt+b∘dWdX = a\,dt + b\circ dW is the same process as the Itô SDE with drift a+12b bxa + \tfrac12 b\,b_x. Physical noise with a short but nonzero correlation time leads to the Stratonovich form (the Wong–Zakai theorem). Euler–Maruyama converges to the Itô solution, so convert the drift first. For additive noise (bb does not depend on xx, so bx=0b_x = 0) the two forms are the same. All diffusion models use additive noise.

    Strong and weak convergence #

    Let XNX_N be a numerical solution at time T=NhT = Nh and X(T)X(T) the exact solution driven by the same Brownian path.

    • Strong order γ\gamma: E∣XN−X(T)∣≤ChγE|X_N - X(T)| \le C h^\gamma. This measures pathwise accuracy.
    • Weak order qq: ∣Ef(XN)−Ef(X(T))∣≤Chq|E f(X_N) - E f(X(T))| \le C h^q for smooth test functions ff. This measures how well the distribution is reproduced.
    Scheme Update Strong order Weak order
    Euler–Maruyama Xn+ah+b ΔWX_n + a h + b\,\Delta W 1/2 (1 if bx=0b_x = 0) 1
    Milstein EM + 12 b bx((ΔW)2−h)+\ \tfrac12\,b\,b_x\big((\Delta W)^2 - h\big) 1 1
    Where the Milstein term comes from (Itô–Taylor expansion)

    Over one step, Xtn+1=Xn+∫a ds+∫b(Xs) dWsX_{t_{n+1}} = X_n + \int a\,ds + \int b(X_s)\,dW_s. EM freezes bb at XnX_n. Expand once more: by Itô's lemma, b(Xs)≈b(Xn)+bxb (Ws−Wtn)b(X_s) \approx b(X_n) + b_x b\,(W_s - W_{t_n}) to leading order. The extra term is b bx∫tntn+1(Ws−Wtn) dWsb\,b_x\int_{t_n}^{t_{n+1}}(W_s - W_{t_n})\,dW_s. By Example 1 applied to the increment Ws−WtnW_s - W_{t_n}, this integral equals 12((ΔW)2−h)\tfrac12\big((\Delta W)^2 - h\big).

    Why EM has strong order 1/2 but weak order 1. The term that EM drops, 12b bx((ΔW)2−h)\tfrac12 b\,b_x((\Delta W)^2 - h), has mean zero and standard deviation 12∣b bx∣ h\tfrac{1}{\sqrt2}|b\,b_x|\,h per step.

    1. Pathwise, N=T/hN = T/h such errors with mean zero add like a random walk: the total is of size N⋅h=Th=O(h1/2)\sqrt N\cdot h = \sqrt{Th} = O(h^{1/2}).
    2. In expectation they cancel. What remains is a bias of O(h2)O(h^2) per step, so the total is N⋅h2=O(h)N\cdot h^2 = O(h): weak order 1.
    3. Milstein keeps the term. Its leftover pathwise error per step is O(h3/2)O(h^{3/2}), and the strong order rises to 1. Its weak order stays 1.
    4. For additive noise (bb constant) the term is zero. EM then already is Milstein and has strong order 1.
    Interactive figure: loading…

    Read the slopes. For GBM, 2000 Brownian paths are shared by all step sizes and by the exact solution. The EM strong error falls with slope about 1/2, the Milstein strong error with slope about 1, and the weak error ∣EXN−EX(T)∣=∣(1+μh)N−eμT∣|E X_N - E X(T)| = |(1 + \mu h)^N - e^{\mu T}| (the same for both schemes) with slope 1. Grey dashed lines show slopes 1/2 and 1. Choose small noise: the EM error is then smaller, but its slope is still 1/2 once hh is small.

    Measuring the orders. For the strong error, every step size must see the same Brownian path: draw the finest increments once and sum blocks of them for the coarser grids. With independent paths the error would not go to zero; it would measure the spread of the process. For the weak error, the Monte Carlo noise s/Ms/\sqrt M (MM paths, sample standard deviation ss) must be well below the bias.

    Quick check

    You want to estimate E[XT]E[X_T] for a climate statistic with an SDE solver. Which property of the solver decides how fast your bias falls with the step size hh?

    4. Worked example #

    (a) One step of GBM. Let x0=1x_0 = 1, μ=0.05\mu = 0.05, σ=0.2\sigma = 0.2, h=0.25h = 0.25, and suppose the Brownian increment is ΔW=0.3\Delta W = 0.3.

    1. EM: the drift term is μx0h=0.05⋅0.25=0.0125\mu x_0 h = 0.05\cdot 0.25 = 0.0125 and the noise term is σx0 ΔW=0.2⋅0.3=0.06\sigma x_0\,\Delta W = 0.2\cdot 0.3 = 0.06. So the EM value after one step is 1+0.0125+0.06=1.07251 + 0.0125 + 0.06 = 1.0725.
    2. Milstein term: b=σxb = \sigma x, so bx=σb_x = \sigma and b bx=σ2x0=0.04b\,b_x = \sigma^2 x_0 = 0.04. With (ΔW)2−h=0.09−0.25=−0.16(\Delta W)^2 - h = 0.09 - 0.25 = -0.16, the term is 12⋅0.04⋅(−0.16)=−0.0032\tfrac12\cdot 0.04\cdot(-0.16) = -0.0032. Milstein: 1.0725−0.0032=1.06931.0725 - 0.0032 = 1.0693.
    3. Exact (Itô's lemma): the exponent is (0.05−0.02)⋅0.25+0.2⋅0.3=0.0675(0.05 - 0.02)\cdot 0.25 + 0.2\cdot 0.3 = 0.0675, so X(h)=e0.0675=1.06983X(h) = e^{0.0675} = 1.06983.
    4. Errors: EM 2.7⋅10−32.7\cdot10^{-3}, Milstein 5.3⋅10−45.3\cdot10^{-4}. The Milstein term removed about 80 % of the EM error on this path.
    5. Over T=1T = 1: the mean of X1X_1 is e0.05=1.0513e^{0.05} = 1.0513 and the median is e0.03=1.0305e^{0.03} = 1.0305. The Itô correction −σ2/2=−0.02-\sigma^2/2 = -0.02 lowers the growth rate of log⁡X\log X.

    (b) An OU process. Let θ=2\theta = 2, σ=1\sigma = 1, x0=1x_0 = 1.

    1. At t=0.5t = 0.5: the mean is e−2⋅0.5=e−1=0.368e^{-2\cdot 0.5} = e^{-1} = 0.368. The variance is 14(1−e−2)\tfrac{1}{4}(1 - e^{-2}), that is 0.25⋅0.8647=0.2160.25\cdot 0.8647 = 0.216.
    2. Stationary: variance σ2/(2θ)=1/4\sigma^2/(2\theta) = 1/4, standard deviation 1/21/2; the memory time is 1/θ=0.51/\theta = 0.5.
    3. Exact transition with Δ=0.1\Delta = 0.1: e−0.2=0.819e^{-0.2} = 0.819 and (1−e−0.4)/4=0.287\sqrt{(1 - e^{-0.4})/4} = 0.287, so Xn+1=0.819 Xn+0.287 ZX_{n+1} = 0.819\,X_n + 0.287\,Z with Z∼N(0,1)Z \sim \mathcal N(0, 1). This is exact for any Δ\Delta.
    4. Fokker–Planck: a=−2xa = -2x, b=1b = 1, so ∂tp=∂x(2x p)+12∂xxp\partial_t p = \partial_x(2x\,p) + \tfrac12\partial_{xx}p.
    5. Zero flux: −2x p=12p′-2x\,p = \tfrac12 p', so p′/p=−4xp'/p = -4x and p∝e−2x2p \propto e^{-2x^2}. Compare with e−x2/(2v)e^{-x^2/(2v)}: 1/(2v)=21/(2v) = 2, so v=1/4v = 1/4. ✓

    5. In code #

    The worked example, a finite-difference check that the OU density solves the Fokker–Planck equation, the quadratic variation, and the weak error of EM:

    import numpy as np
    from scipy.stats import chi2
    
    # (a) One step of GBM: Euler-Maruyama, Milstein and the exact solution on the same increment
    x0, mu, sigma, h, dW = 1.0, 0.05, 0.2, 0.25, 0.3
    em = x0 + mu * x0 * h + sigma * x0 * dW
    mil = em + 0.5 * (sigma * x0) * sigma * (dW**2 - h)        # b b_x = (sigma x) sigma
    exact = x0 * np.exp((mu - sigma**2 / 2) * h + sigma * dW)  # Ito's lemma on log X
    print(f"{em:.4f} {mil:.4f} {exact:.5f}")                    # 1.0725 1.0693 1.06983
    print(f"{abs(em - exact):.1e} {abs(mil - exact):.1e}")      # 2.7e-03 5.3e-04
    
    # (b) OU with theta = 2, sigma = 1, x0 = 1
    theta, sig, x0 = 2.0, 1.0, 1.0
    t = 0.5
    print(f"{x0 * np.exp(-theta * t):.3f} {sig**2 / (2 * theta) * (1 - np.exp(-2 * theta * t)):.3f}")  # 0.368 0.216
    D = 0.1
    print(f"{np.exp(-theta * D):.3f} {np.sqrt(sig**2 / (2 * theta) * (1 - np.exp(-2 * theta * D))):.3f}")  # 0.819 0.287
    
    # The OU density N(m(t), v(t)) solves p_t = d/dx(theta x p) + (sigma^2/2) p_xx: finite-difference residual
    x = np.linspace(-3, 3, 601); dx = x[1] - x[0]; dt = 1e-5
    def p(t):
        m, v = x0 * np.exp(-theta * t), sig**2 / (2 * theta) * (1 - np.exp(-2 * theta * t))
        return np.exp(-(x - m)**2 / (2 * v)) / np.sqrt(2 * np.pi * v)
    pt = (p(t + dt) - p(t - dt)) / (2 * dt)
    rhs = np.gradient(theta * x * p(t), dx) + sig**2 / 2 * np.gradient(np.gradient(p(t), dx), dx)
    print(f"max |p_t| = {abs(pt).max():.2f}, max residual = {abs(pt - rhs).max():.1e}")
    # max |p_t| = 0.86, max residual = 5.4e-04
    
    # (c) Quadratic variation: the sum of N squared increments is h * chi2(N)
    for N in (10, 1_000, 100_000):
        hN = 1.0 / N
        print(f"N = {N:6d}: QV mean {chi2(N, scale=hN).mean():.3f}, QV std {chi2(N, scale=hN).std():.4f}, "
              f"E[TV] {N * np.sqrt(2 * hN / np.pi):6.1f}")
    # N =     10: QV mean 1.000, QV std 0.4472, E[TV]    2.5
    # N =   1000: QV mean 1.000, QV std 0.0447, E[TV]   25.2
    # N = 100000: QV mean 1.000, QV std 0.0045, E[TV]  252.3
    
    # (d) Weak error of EM in the mean of GBM: E[X_{n+1}] = (1 + mu h) E[X_n] exactly
    mu, T = 2.0, 1.0
    errs = np.array([abs((1 + mu * T / N)**N - np.exp(mu * T)) for N in (16, 32, 64, 128)])
    print(np.round(errs, 4), np.round(errs[:-1] / errs[1:], 3))
    # [0.8058 0.4304 0.2228 0.1134] [1.872 1.932 1.965]
    

    The finite-difference residual (5⋅10−45\cdot10^{-4}) is the discretisation error of the check itself; it falls when you refine dx. The weak-error ratios approach 2: weak order 1. The strong orders, measured on coupled paths:

    rng = np.random.default_rng(0)
    mu, sigma, T, M, NF = 1.0, 1.0, 1.0, 4000, 512
    dWf = np.sqrt(T / NF) * rng.standard_normal((M, NF))        # one set of fine increments
    XT = np.exp((mu - sigma**2 / 2) * T + sigma * dWf.sum(1))    # exact X(T) on every path
    hs, e_em, e_mil = [], [], []
    for N in (8, 16, 32, 64, 128, 256):
        dW = dWf.reshape(M, N, -1).sum(2)                        # the same paths on a coarser grid
        h = T / N
        xe = np.ones(M); xm = np.ones(M)
        for n in range(N):
            d = dW[:, n]
            xe = xe + mu * xe * h + sigma * xe * d
            xm = xm + mu * xm * h + sigma * xm * d + 0.5 * sigma**2 * xm * (d**2 - h)
        hs.append(h); e_em.append(np.mean(abs(xe - XT))); e_mil.append(np.mean(abs(xm - XT)))
    slope = lambda e: np.polyfit(np.log(hs), np.log(e), 1)[0]
    print(f"strong order: EM {slope(e_em):.2f}, Milstein {slope(e_mil):.2f}")
    # strong order: EM 0.49, Milstein 0.96
    

    6. Where it shows up #

    • Diffusion models. The variance-preserving forward SDE dX=−12β(t)X dt+β(t) dWdX = -\tfrac12\beta(t)X\,dt + \sqrt{\beta(t)}\,dW is an OU process with a time-dependent rate. The proof of Theorem 2 gives Xt∣X0∼N(αtX0,(1−αt2)I)X_t \mid X_0 \sim \mathcal N\big(\alpha_t X_0, (1 - \alpha_t^2)I\big) with αt=exp⁡(−12∫0tβ(s) ds)\alpha_t = \exp\big(-\tfrac12\int_0^t\beta(s)\,ds\big). Training draws xtx_t from this formula in one step (generative models 07).
    • The probability-flow ODE. For dX=a dt+g(t) dWdX = a\,dt + g(t)\,dW in dd dimensions, the diffusion term can be written as a flux: 12g2Δp=∇⋅(12g2 p ∇log⁡p)\tfrac12 g^2\Delta p = \nabla\cdot\big(\tfrac12 g^2\,p\,\nabla\log p\big). So the Fokker–Planck equation becomes a pure transport equation with velocity a−12g2∇log⁡pa - \tfrac12 g^2\nabla\log p, and the ODE with this velocity has the same marginals as the SDE. This is the probability-flow ODE of lesson 13.
    • Langevin samplers. EM applied to dX=∇log⁡π dt+2 dWdX = \nabla\log\pi\,dt + \sqrt2\,dW is the unadjusted Langevin algorithm (ULA). Its stationary distribution is off by O(h)O(h), a weak error. MALA removes this bias with a Metropolis–Hastings step (probability 15); score-based samplers use the same update with a learned score (generative models 06).
    • Climate. Hasselmann's stochastic climate model (1976) treats the slow ocean temperature as integrating fast weather noise, dT=−λT dt+σ dWdT = -\lambda T\,dt + \sigma\,dW: an OU process. Its spectrum is "red" (large at low frequencies), as observed for sea-surface temperature. Ensemble weather prediction perturbs the tendencies of the physics parametrisations with random patterns that evolve in time as AR(1) processes, that is, discretised OU processes (the SPPT scheme: Buizza et al. 1999; Palmer et al. 2009).
    • Seismology. The Kanai–Tajimi model of earthquake ground acceleration is the output of a damped oscillator (the soil layer) driven by white noise: a linear SDE in two variables, whose stationary covariance follows from the same Itô and Fokker–Planck tools. In earthquake forecasting, the Brownian passage time model (Matthews et al. 2002) describes the time between large earthquakes on a fault as the first time a Brownian motion with drift reaches a failure threshold.
    • Strong or weak? Diffusion sampling and climate statistics need only the distribution: weak order. Pathwise questions (a given noise realisation, coupled comparisons, multilevel Monte Carlo) need strong order.
    • Finance. GBM is the Black–Scholes model of a stock price; the −σ2/2-\sigma^2/2 in its log-return is Itô's lemma.

    7. Common mistakes #

    • Forgetting the Itô term. For example, writing dlog⁡X=μ dt+σ dWd\log X = \mu\,dt + \sigma\,dW for GBM. The correct drift is μ−σ2/2\mu - \sigma^2/2.
    • Increments with standard deviation hh. A Brownian increment over a step hh has standard deviation h\sqrt h: np.sqrt(h) * rng.standard_normal().
    • Evaluating the coefficients at the new point or the midpoint in EM. The new point makes the scheme implicit, the midpoint changes the limit toward Stratonovich. Itô means the left point.
    • Mixing Itô and Stratonovich models. Convert the drift (a→a+12b bxa \to a + \tfrac12 b\,b_x) before you use EM on a Stratonovich SDE.
    • Measuring the strong error with independent paths. The numerical and the exact solution must use the same Brownian increments; otherwise the "error" does not go to zero.
    • Weak errors hidden by Monte Carlo noise. You need s/Ms/\sqrt M well below ChCh; compare schemes on the same paths to cancel most of the noise.
    • Expecting Milstein to help with additive noise. bx=0b_x = 0, so Milstein equals EM, which then already has strong order 1.
    • OU stationary variance σ2/θ\sigma^2/\theta. The correct value is σ2/(2θ)\sigma^2/(2\theta).
    • Writing 12b2 ∂xxp\tfrac12 b^2\,\partial_{xx}p in the Fokker–Planck equation instead of 12∂xx(b2p)\tfrac12\partial_{xx}(b^2p). The two differ when bb depends on xx.

    8. Check yourself #

    1. Compute d(Wt3)d(W_t^3) with Itô's lemma and use it to show E[Wt3]=0E[W_t^3] = 0.
      Answerf=x3f = x^3, fx=3x2f_x = 3x^2, fxx=6xf_{xx} = 6x: d(W3)=3W2 dW+3W dtd(W^3) = 3W^2\,dW + 3W\,dt. Taking expectations, ddtE[Wt3]=3E[Wt]=0\frac{d}{dt}E[W_t^3] = 3E[W_t] = 0, and W03=0W_0^3 = 0, so E[Wt3]=0E[W_t^3] = 0 for all tt.
    2. For GBM, find E[Xt2]E[X_t^2] with Itô's lemma.
      Answerf=x2f = x^2: d(X2)=(2μX2+σ2X2) dt+2σX2 dWd(X^2) = (2\mu X^2 + \sigma^2X^2)\,dt + 2\sigma X^2\,dW. So ddtEX2=(2μ+σ2) EX2\frac{d}{dt}E X^2 = (2\mu + \sigma^2)\,E X^2 and EXt2=x02e(2μ+σ2)tE X_t^2 = x_0^2e^{(2\mu + \sigma^2)t}. The variance is x02e2μt(eσ2t−1)x_0^2e^{2\mu t}(e^{\sigma^2t} - 1).
    3. Write the Fokker–Planck equation of dX=−X3 dt+2 dWdX = -X^3\,dt + \sqrt2\,dW and its stationary density.
      Answer∂tp=∂x(x3p)+∂xxp\partial_t p = \partial_x(x^3p) + \partial_{xx}p. Zero flux: −x3p−p′=0-x^3p - p' = 0, so p∝e−x4/4p \propto e^{-x^4/4}. This is Langevin dynamics with U=x4/4U = x^4/4.
    4. A study on shared Brownian paths gives errors 0.0400.040, 0.0280.028, 0.0200.020 for hh, h/2h/2, h/4h/4. Which order is this, and which scheme and noise type could produce it?
      AnswerEach ratio is about 2\sqrt2, so the order is 1/21/2. This is the strong error of Euler–Maruyama with multiplicative noise (bx≠0b_x \ne 0), for example on GBM.
    5. Why does Milstein give no gain over EM for the OU process?
      AnswerThe noise is additive: b=σb = \sigma is constant, bx=0b_x = 0, so the Milstein term vanishes. EM is then the same scheme as Milstein and already has strong order 1.
    6. Is Mt=Wt2−tM_t = W_t^2 - t a martingale (a process with no drift)? Is eσWte^{\sigma W_t}?
      AnswerdM=2W dW+dt−dt=2W dWdM = 2W\,dW + dt - dt = 2W\,dW: no drift, so yes. For eσWte^{\sigma W_t} Itô gives the drift 12σ2eσWt≠0\tfrac12\sigma^2e^{\sigma W_t} \ne 0, so no. The process eσWt−σ2t/2e^{\sigma W_t - \sigma^2t/2} is a martingale: its ftf_t term cancels the Itô term.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the distribution of a Brownian increment Wt+h−WtW_{t+h} - W_t?

    2. What does the quadratic variation ∑k(ΔWk)2\sum_k(\Delta W_k)^2 of Brownian motion on [0,T][0, T] converge to, and what rule does this give?

    3. State Itô's lemma for Y=f(X,t)Y = f(X, t) with dX=a dt+b dWdX = a\,dt + b\,dW.

    4. Write one Euler–Maruyama step for dX=a(X,t) dt+b(X,t) dWdX = a(X, t)\,dt + b(X, t)\,dW.

    5. Why does the median of GBM grow at rate μ−σ2/2\mu - \sigma^2/2 and not μ\mu?

    6. What is the stationary distribution of the OU process dX=−θX dt+σ dWdX = -\theta X\,dt + \sigma\,dW?

    7. Write the 1D Fokker–Planck equation of dX=a dt+b dWdX = a\,dt + b\,dW.

    8. What is the stationary density of dX=−U′(X) dt+2 dWdX = -U'(X)\,dt + \sqrt 2\,dW, and how do you get it?

    9. Strong vs weak order: what does each measure, and what are they for Euler–Maruyama?

    Open the review →

    9. Interview angle #

    • "Why is there a −σ2/2-\sigma^2/2 in the solution of GBM?" Itô's lemma on log⁡X\log X: fxx=−1/x2f_{xx} = -1/x^2 gives −12σ2-\tfrac12\sigma^2. The mean grows at rate μ\mu, the median at rate μ−σ2/2\mu - \sigma^2/2.
    • "What is the Fokker–Planck equation, and how is it used in diffusion models?" The PDE for the density of an SDE. Rewritten as a continuity equation, it gives the probability-flow ODE with the same marginals.
    • "Strong or weak convergence: which one matters for a generative sampler?" Weak: you care about the distribution of the samples, not about matching one particular noise path.
    • "Itô or Stratonovich?" Itô: left point, zero-mean integrals, EM converges to it. Stratonovich: midpoint, ordinary chain rule, the limit of smooth noise. Convert with a→a+12b bxa \to a + \tfrac12 b\,b_x; for additive noise they agree.
    • "How do you test an SDE solver?" Moments against closed forms, a strong-order study on coupled paths, a weak-order study with error bars, and stationary histograms against the Fokker–Planck solution.

    10. Practice #

    The notebook for this lesson runs in Colab or in the browser. It has five exercises, each with a check cell and a folded solution:

    1. Brownian paths from Gaussian increments; total and quadratic variation as the grid is refined.
    2. Euler–Maruyama and Milstein for a general scalar SDE; check them on the worked example.
    3. A convergence study on GBM with coupled paths: measured strong orders near 0.5 (EM) and 1.0 (Milstein), and the weak order of EM in E[XT]E[X_T].
    4. Itô's lemma as a function: drift and diffusion of f(X,t)f(X, t); check it on log⁡\log of GBM and by Monte Carlo for eWte^{W_t}.
    5. Exact OU sampling with the Gaussian transition; the long-run histogram against N(0,σ2/2θ)\mathcal N(0, \sigma^2/2\theta).

    11. Watch and read #

    Itô's lemma from the second-order Taylor expansion and the rule (dW)² = dt (MIT 18.S096).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    What it means to solve an SDE, and how Itô's lemma solves simple ones.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A visual introduction to the Itô integral as a limit of left-point sums.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Brownian motion and the OU process from the physics side (Langevin equation, Einstein relation).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    ODEs, SDEs, Euler–Maruyama and the OU process as the building blocks of diffusion models.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play