Stochastic differential equations, Itô calculus and the Fokker–Planck equation
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 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 by simulating an SDE whose stationary density is . The zero-flux condition of the Fokker–Planck equation proves that this works.
1. Predict first #
2. The picture #
Brownian motion: kicks of size #
Brownian motion (also called the Wiener process) is the simplest random path. It starts at , it is continuous, and its increments are independent Gaussians:
So a step of length moves the path by a random amount with standard deviation . For small , is much larger than : for , . This makes the path very rough. It is continuous, but it has no slope anywhere.
Cut into steps of size and add up the increments in two ways:
- the total variation (the length of the path, seen at resolution ). Each term has mean , so the sum has mean . It grows without limit as ;
- the quadratic variation . Each term has mean , so the sum has mean . Its variance is , which goes to 0.
So the sum of squared increments does not vanish: it converges to exactly . In a smooth function the squares of small changes are and disappear. For Brownian motion, is of order , the same order as . In the limit we write
This one rule produces the extra term of Itô's lemma below.
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 , while the quadratic variation settles at ; grey dashed lines are the expected values, the yellow dots mark the current . Press New path a few times: the quadratic variation is close to 1 on every path when is large.
An SDE is a limit of a simple recipe #
An SDE in one dimension is written
The function is the drift: it moves the mean. The function 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:
Each step adds the mean change and the variance . The coefficients are evaluated at the left point , before the noise of the step is known. This choice defines the Itô interpretation of the SDE. With it is forward Euler for the ODE (lesson 02).
The chain rule gets an extra term #
Take geometric Brownian motion (GBM), : the noise is proportional to . If the ordinary chain rule held, would grow at rate . It does not. Section 3 shows that grows at rate . The mean still grows at rate , but the median (the typical path) grows only at rate . A few large paths pull the mean up.
Increase the volatility and watch the two lines separate. Grey: 40 of 1000 exact GBM paths (log scale). Orange, dashed: the mean , which is also what the ordinary chain rule predicts for the typical path. Blue: the true median . Dots are the sample mean and median of the 1000 paths. Bottom: the histogram of is Gaussian around . Try : 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 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 . The drift pulls back toward 0 at rate ; the noise pushes it away. The two balance in a stationary Gaussian with variance .
Press Play, or move the time . Top: 25 of 2000 OU paths; the dashed blue line is the mean . Bottom: the histogram of all 2000 paths at time , the Fokker–Planck solution and the grey dashed stationary density. Each path is random; the histogram follows one deterministic curve. Increase : the process forgets faster, and the stationary density gets narrower.
A Brownian increment over a step is . What is ?
. The size of is , not , so its square is first order in . That is why the sum of squares over tends to and does not vanish.
3. Definitions and main results #
Brownian motion and the Itô integral #
Brownian motion : ; increments over disjoint intervals are independent; for ; paths are continuous. It follows that .
A process is non-anticipating if depends only on the path up to time , not on the future. For such , the Itô integral is the limit of left-point sums:
Because is independent of the next increment, two properties follow:
- mean zero: ;
- Itô isometry: .
An Itô SDE is shorthand for the integral equation .
Theorem 1 (Itô's lemma) #
Let solve , and let be once differentiable in and twice in . Then solves
Why this is true (intuition). Expand to second order. In ordinary calculus the second-order term is and disappears. Here contains , which is first order, so half of it survives.
Proof sketch
- Taylor-expand over one step:
- Insert : .
- The first two terms are and per step. Over steps they sum to and , which vanish as .
- The last term: has mean and variance . Summed over steps with a bounded weight , the sum has mean and a variance of order . So in the limit can be replaced by .
- Third-order terms such as are per step and sum to .
- Collect the terms and the term.
The rules to remember are , , . With the lemma is the ordinary chain rule. The new term is the Itô correction. For a convex it is positive: noise pushes up on average (this is Jensen's inequality, ).
Example 1. and (, ): , , so . Taking expectations, and .
Example 2: geometric Brownian motion. . Take , so , :
The right side has constant coefficients, so we can integrate it directly:
The median of is (the median of is 0). The mean is , because (the moment generating function of ).
By Itô's lemma, what is ?
has and ; with , the correction is . The first option is the ordinary chain rule; it would give , which is impossible.
Theorem 2 (the Ornstein–Uhlenbeck process) #
The OU process with mean-reversion rate , noise level and has the solution
Proof
- Use an integrating factor, as for the linear ODE : let , that is with , , .
- Itô's lemma: . There is no correction term, because is linear in .
- Integrate from 0 to : . Multiply by .
- The integral of a deterministic function against is a limit of sums of independent Gaussians, so it is Gaussian, with mean 0.
- Its variance, by the Itô isometry, is .
As the mean goes to 0 and the variance to : the stationary distribution is . The time scale of the memory is .
The same argument over one step of length gives the exact transition
So an OU process sampled every is an AR(1) process (time series 05) with coefficient , and this sampling has no step-size error. With a mean level , , replace by everywhere.
An OU process has and . What is its stationary variance?
, so the stationary standard deviation is . The answer comes from the common mistake , which forgets the factor 2 from .
Theorem 3 (Fokker–Planck equation) #
Let solve with smooth and , and let have a smooth density . Then
The first term is advection (the drift carries probability), the second is diffusion (the noise spreads it). Note that stays inside the second derivative.
Proof (from Itô's lemma)
- Take any smooth test function that is zero outside a bounded set. By Itô's lemma, .
- Take expectations. The term has mean zero: .
- Write both sides as integrals against the density: .
- Integrate by parts, once for the term and twice for the term. The boundary terms vanish because does: .
- This holds for every test function , so the two functions in brackets are equal.
The operator in step 2 is the generator of the SDE. The Fokker–Planck operator is its adjoint: integration by parts moves the derivatives from to . This is the same "move the derivative to the other factor" idea as in the adjoint methods of lesson 03.
Fokker–Planck in dimensions
For with , and a matrix, let . Then
For the diffusion-model case (the same noise in every direction, independent of ) this is , where is the Laplacian. Lesson 13 starts from this form.
Stationary densities and probability flux #
Write the 1D equation as a conservation law, , with the probability flux
is the rate at which probability crosses the point from left to right. A stationary density has , so is a constant. On the whole real line, with and decaying in the tails, that constant is 0. This is the zero-flux condition:
- OU (, ): . So and , which is , as in Theorem 2.
- Overdamped Langevin dynamics with a potential : zero flux gives , so , the Gibbs density. With the SDE has as its stationary density. It needs only the derivative of , not the normalising constant of . This derivative is the score, the central object of lesson 13.
- With multiplicative noise ( depends on ), solve the zero-flux equation for : , a first-order linear ODE.
Press Play and watch the fluxes. The density solves the Fokker–Planck equation of with reflecting walls at . Top: the density and the grey dashed Gibbs density . Bottom: the drift flux , the diffusion flux and their sum, the total flux (positive means "to the right"). At stationarity the two fluxes are mirror images and . In the double well, notice the long final phase: a small flux over the barrier at slowly fills the left well.
What is the stationary density of ?
Zero flux gives (here ), so and . With noise instead of the result is , which is the version in the figure.
Itô or Stratonovich?
The Stratonovich integral evaluates 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: (Itô) while (Stratonovich).
A Stratonovich SDE is the same process as the Itô SDE with drift . 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 ( does not depend on , so ) the two forms are the same. All diffusion models use additive noise.
Strong and weak convergence #
Let be a numerical solution at time and the exact solution driven by the same Brownian path.
- Strong order : . This measures pathwise accuracy.
- Weak order : for smooth test functions . This measures how well the distribution is reproduced.
| Scheme | Update | Strong order | Weak order |
|---|---|---|---|
| Euler–Maruyama | 1/2 (1 if ) | 1 | |
| Milstein | EM | 1 | 1 |
Where the Milstein term comes from (Itô–Taylor expansion)
Over one step, . EM freezes at . Expand once more: by Itô's lemma, to leading order. The extra term is . By Example 1 applied to the increment , this integral equals .
Why EM has strong order 1/2 but weak order 1. The term that EM drops, , has mean zero and standard deviation per step.
- Pathwise, such errors with mean zero add like a random walk: the total is of size .
- In expectation they cancel. What remains is a bias of per step, so the total is : weak order 1.
- Milstein keeps the term. Its leftover pathwise error per step is , and the strong order rises to 1. Its weak order stays 1.
- For additive noise ( constant) the term is zero. EM then already is Milstein and has strong order 1.
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 (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 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 ( paths, sample standard deviation ) must be well below the bias.
You want to estimate for a climate statistic with an SDE solver. Which property of the solver decides how fast your bias falls with the step size ?
depends only on the distribution of , so the bias is the weak error, of order . The strong order matters for pathwise questions (one particular noise realisation, coupled comparisons). The Monte Carlo error is a separate, second error.
4. Worked example #
(a) One step of GBM. Let , , , , and suppose the Brownian increment is .
- EM: the drift term is and the noise term is . So the EM value after one step is .
- Milstein term: , so and . With , the term is . Milstein: .
- Exact (Itô's lemma): the exponent is , so .
- Errors: EM , Milstein . The Milstein term removed about 80 % of the EM error on this path.
- Over : the mean of is and the median is . The Itô correction lowers the growth rate of .
(b) An OU process. Let , , .
- At : the mean is . The variance is , that is .
- Stationary: variance , standard deviation ; the memory time is .
- Exact transition with : and , so with . This is exact for any .
- Fokker–Planck: , , so .
- Zero flux: , so and . Compare with : , so . ✓
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 () 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 is an OU process with a time-dependent rate. The proof of Theorem 2 gives with . Training draws from this formula in one step (generative models 07).
- The probability-flow ODE. For in dimensions, the diffusion term can be written as a flux: . So the Fokker–Planck equation becomes a pure transport equation with velocity , 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 is the unadjusted Langevin algorithm (ULA). Its stationary distribution is off by , 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, : 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 in its log-return is Itô's lemma.
7. Common mistakes #
- Forgetting the Itô term. For example, writing for GBM. The correct drift is .
- Increments with standard deviation . A Brownian increment over a step has standard deviation
:
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 () 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 well below ; compare schemes on the same paths to cancel most of the noise.
- Expecting Milstein to help with additive noise. , so Milstein equals EM, which then already has strong order 1.
- OU stationary variance . The correct value is .
- Writing in the Fokker–Planck equation instead of . The two differ when depends on .
8. Check yourself #
- Compute with Itô's lemma and use it to show .
Answer
, , : . Taking expectations, , and , so for all . - For GBM, find with Itô's lemma.
Answer
: . So and . The variance is . - Write the Fokker–Planck equation of and its stationary density.
Answer
. Zero flux: , so . This is Langevin dynamics with . - A study on shared Brownian paths gives errors , , for , , . Which order is
this, and which scheme and noise type could produce it?
Answer
Each ratio is about , so the order is . This is the strong error of Euler–Maruyama with multiplicative noise (), for example on GBM. - Why does Milstein give no gain over EM for the OU process?
Answer
The noise is additive: is constant, , so the Milstein term vanishes. EM is then the same scheme as Milstein and already has strong order 1. - Is a martingale (a process with no drift)? Is ?
Answer
: no drift, so yes. For Itô gives the drift , so no. The process is a martingale: its term cancels the Itô term.
What is the distribution of a Brownian increment ?
, independent of the path before time . Its typical size is .
What does the quadratic variation of Brownian motion on converge to, and what rule does this give?
It converges to (mean , variance ). This gives the rule .
State Itô's lemma for with .
.
Write one Euler–Maruyama step for .
with , coefficients at the left point.
Why does the median of GBM grow at rate and not ?
Itô's lemma on : gives the correction , so .
What is the stationary distribution of the OU process ?
.
Write the 1D Fokker–Planck equation of .
.
What is the stationary density of , and how do you get it?
The Gibbs density , from the zero-flux condition .
Strong vs weak order: what does each measure, and what are they for Euler–Maruyama?
Strong: pathwise error on the same Brownian path. Weak: error in expectations . EM: strong 1/2 (1 for additive noise), weak 1.
9. Interview angle #
- "Why is there a in the solution of GBM?" Itô's lemma on : gives . The mean grows at rate , the median at rate .
- "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 ; 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:
- Brownian paths from Gaussian increments; total and quadratic variation as the grid is refined.
- Euler–Maruyama and Milstein for a general scalar SDE; check them on the worked example.
- 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 .
- Itô's lemma as a function: drift and diffusion of ; check it on of GBM and by Monte Carlo for .
- Exact OU sampling with the Gaussian transition; the long-run histogram against .
11. Watch and read #
- Särkkä and Solin, Applied Stochastic Differential Equations (free PDF, 2019): §4.1–4.3 (Itô integral and Itô formula, the OU solution), §4.6 (Stratonovich), §5.2 (Fokker–Planck–Kolmogorov equation, stationary solutions), §8.2–8.3 (Euler–Maruyama, Milstein, strong and weak order).
- D. J. Higham, An algorithmic introduction to numerical simulation of stochastic differential equations, SIAM Review 43 (2001): §4 (EM), §5 (strong and weak convergence), §6 (Milstein), §8 (stochastic chain rule). Short, with MATLAB code for every figure.
- Holderrieth and Erives, MIT 6.S184 lecture notes (2026): §2.2 (SDEs, the OU process, Euler–Maruyama), §4.2 (Fokker–Planck and Langevin dynamics); lab one of the course labs simulates the same processes.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.