Module contents
Lesson 28 of 31Advanced 115 min

Generator, Kolmogorov, Fokker-Planck and Feynman-Kac

Connect SDEs and PDEs through the infinitesimal generator, Dynkin's formula, backward Kolmogorov and forward Fokker-Planck equations, stationary densities, exit times and Feynman-Kac.

After this lesson you can

  • Calculate a diffusion generator and use Dynkin's formula for exit probabilities and expected times.
  • Derive backward Kolmogorov and Fokker-Planck equations and explain their adjoint relationship.
  • Obtain stationary densities of scalar and gradient diffusions and check them by simulation.
  • Solve a parabolic PDE with Feynman-Kac Monte Carlo and compare with finite differences.
  • Relate Fokker-Planck density evolution to continuity and probability current.

Before you start

One law, two ways to evolve

A particle follows a random path; a density describes where a collection of particles may be found. To value a payoff, estimate the probability of escaping a safe region or understand a generative model, you can simulate paths or solve an equation for their probabilities. The descriptions are connected but ask about different variables.

In the figure, density equation and particles share drift, diffusion and boundary. Change the potential and observe how mass is distributed. Discrepancy between histogram and curve includes Monte Carlo fluctuation and discretization errors; conserving mass does not guarantee the numerical density is exact.

InteractiveParticles and density

We compare 1200 particles with a density on 48 cells on a circle: −π and π are the same point. Both start from a wrapped Gaussian with deviation 0.45 and evolve until T=4. Histogram lines connect cell heights; they do not represent a smoothed density.

  • Fokker–Planck by finite volumes
  • Particle histogram
  • Continuous stationary density

Model: dX=b(X)dt+√(2D)dB, with position reduced modulo 2π. For one well, b(x)=−κ sin(x) and U(x)=κ(1−cos x). Continuous stationary density is proportional to exp(−U/D), normalized here on the grid; the discrete scheme has its own approximate stationary distribution.

Fokker–Planck satisfies ∂ₜp=−∂ₓ(bp)+D∂ₓ²p. Each flux between cells uses upwind transport and centered diffusion; flux leaving one cell enters its neighbor, including across the periodic boundary. The chosen step condition keeps coefficients nonnegative. Particles use Euler–Maruyama with the same time step and periodic wrapping: discretization error and sampling noise remain.

The displayed distance is half the sum of absolute differences between cell masses. It need not be zero for a finite sample. Numerical mass and minimum density allow conservation and positivity checks; neither visual agreement nor finite time proves equilibrium.

Potential
Initial distribution
1.0
0.35
2.0
Time2.0
Fokker–Planck mass1.000000
Minimum density0.026993
Distance between cell masses0.076
Numerical step0.01250
Particles1200
Seed2628
Compare a simulated cloud with conservative Fokker-Planck evolution.

The infinitesimal generator

For Itô diffusion dXt=b(Xt)dt+σ(Xt)dWtdX_t=b(X_t)dt+\sigma(X_t)dW_t, with Xt∈RdX_t\in\mathbb R^d, a=σσTa=\sigma\sigma^\mathsf T and coefficients ensuring a nonexplosive solution, the generator acts on sufficiently regular functions:

Lf(x)=b(x)⋅∇f(x)+12∑i,jaij(x) ∂ijf(x).Lf(x)=b(x)\cdot\nabla f(x)+\frac12\sum_{i,j}a_{ij}(x)\,\partial_{ij}f(x).

For f∈Cc2f\in C_c^2 and under the usual assumptions permitting passage to the limit, Lf(x)=lim⁡h↓0[Exf(Xh)−f(x)]/hLf(x)=\lim_{h\downarrow0}[E_x f(X_h)-f(x)]/h. The first term is transport; the second comes from quadratic variation. It is analogous to the generator matrix of a continuous-time chain: both describe instantaneous change in a state function.

Applying Itô and integrating gives Dynkin’s formula. If τ\tau is a stopping time and the integrals are integrable, then

Exf(Xt∧τ)=f(x)+Ex∫0t∧τLf(Xs) ds.E_x f(X_{t\wedge\tau})=f(x)+E_x\int_0^{t\wedge\tau}Lf(X_s)\,ds.

Bounded stopping and integrability assumptions allow the stochastic term to have zero expectation. Removing the time limit or using unbounded functions requires justification of convergence and boundary conditions.

Let τ\tau be the first exit from a regular domain and AA part of its boundary. If Lu=0Lu=0 inside, u=1u=1 on AA and u=0u=0 on the remainder, Dynkin identifies u(x)=Px(Xτ∈A)u(x)=P_x(X_\tau\in A) under assumptions guaranteeing exit and a solution. Mean time v(x)=Exτv(x)=E_x\tau satisfies Lv=−1Lv=-1 inside and v=0v=0 on the boundary when finite. Points where the boundary condition changes abruptly may require appropriate interpretation.

InteractiveExit through the chosen boundary

Blue marks the grid domain; intensity indicates calculated probability. Adjacent green exterior cells are the target boundary, other exterior cells are unwanted exits. The dark point is the start.

  • Domain, intensity = probability
  • Target boundary
  • First steps of three walks

Tap an interior cell to choose the start. In domain mode, drag to add or remove cells; the outer border remains free. In target mode, tap or drag over exterior cells sharing a side with the domain. Lines show only the first 60 steps of three walks; every full walk is used in the estimate.

For standard Brownian motion, L = Δ/2 and exit probability u satisfies Lu = 0 with value 1 on the target boundary and 0 elsewhere, under the usual Dirichlet problem assumptions. Here we solve its approximation on a grid of 21 × 21: each interior cell equals the average of its four neighbors, and the discrete boundary consists of adjacent exterior cells. Discretization shifts the boundary and pixel roughness matters; the result is not an exact continuous solution.

The 600 walks jump with equal probability to any of the four neighboring cells and use exactly the same boundary as the linear system. A walk that has not exited after 4000 steps is censored, not counted as failure. The conservative 95% band combines possible future exits of censored walks with a Hoeffding bound; it depends on simulations. Residual measures the discrete equation, not error relative to the continuous domain.

Tool
Discrete solution at start0.199
Exits at target109 / 600
Censored0
95% Monte Carlo band12.6 % to 23.7 %
Maximum residual2.02e-9
Solver sweeps80
Active target cells9
Seed2628
Draw a grid domain, mark the target boundary and compare the discrete problem with paths.

For standard Brownian motion on (−1,1)(-1,1), L=12∂xxL=\tfrac12\partial_{xx} and v′′=−2v''=-2 with v(±1)=0v(\pm1)=0, so v(x)=1−x2v(x)=1-x^2. The numerical exercise asks you to evaluate this solution at another position. The figure uses a discrete domain and walk: its results approximate the continuous problem under refinement and suitable conditions; they are not exact continuous Brownian paths.

Backward and forward

For terminal payoff gg, define u(t,x)=E[g(XT)∣Xt=x]u(t,x)=E[g(X_T)\mid X_t=x] in a homogeneous model. The Markov property gives u(t,x)=Exu(t+h,Xh)u(t,x)=E_x u(t+h,X_h). Expanding in hh, or applying Itô to u(s,Xs)u(s,X_s), yields the backward Kolmogorov equation

∂tu+Lu=0,u(T,x)=g(x).\partial_t u+Lu=0,\qquad u(T,x)=g(x).

Variable xx represents the initial state of the remaining interval and a terminal condition is prescribed. This derivation requires sufficient regularity of uu and an integrable martingale; when regularity is absent, weaker solution notions are used.

For law p(t,x)p(t,x), by contrast, an initial condition is prescribed. If ff is smooth and compactly supported, Itô and expectation give ddt∫fp=∫(Lf)p\frac{d}{dt}\int fp=\int (Lf)p. Integration by parts yields adjoint L∗L^* and the Fokker-Planck equation:

∂tp=L∗p=−∑i∂i(bip)+12∑i,j∂ij(aijp).\partial_t p=L^*p=-\sum_i\partial_i(b_i p) +\frac12\sum_{i,j}\partial_{ij}(a_{ij}p).

State-dependent diffusion remains inside both derivatives. Integration by parts requires boundary conditions that cancel or account for edge terms. In one dimension, with a=σ2a=\sigma^2, this is a continuity equation ∂tp=−∂xJ\partial_t p=-\partial_x J, where

J=bp−12∂x(ap).J=bp-\tfrac12\partial_x(ap).

A reflecting boundary imposes zero normal current; an absorbing boundary loses mass from the domain and the loss represents exit. On a circle endpoints are identified and flows leaving one enter the other. These conditions describe different processes.

Equilibrium and current

A stationary density satisfies L∗π=0L^*\pi=0 and the boundary conditions. In one dimension, where stationary flow is zero and a>0a>0 in the interior,

π(x)=Ca(x)exp⁡(∫x2b(y)a(y) dy),\pi(x)=\frac{C}{a(x)} \exp\left(\int^x\frac{2b(y)}{a(y)}\,dy\right),

if the expression is integrable and satisfies the boundary. Normalization and endpoint behavior are part of the problem. For dX=−U′(X)dt+2D dBdX=-U'(X)dt+\sqrt{2D}\,dB, D>0D>0, this gives π∝e−U/D\pi\propto e^{-U/D} when the density is normalizable and flow is zero. In CIR we recover the previous lesson’s Gamma law, with shape 2κθ/σ22\kappa\theta/\sigma^2 and scale σ2/(2κ)\sigma^2/(2\kappa).

This law explains the use of Langevin for sampling. Discretizing continuous dynamics introduces bias; MALA adds a Metropolis acceptance correction to preserve the target distribution under its assumptions.

Stationarity does not imply reversibility. Consider dX=(−κI+ωR)Xdt+2D dWdX=(-\kappa I+\omega R)Xdt+\sqrt{2D}\,dW, with R(x,y)=(−y,x)R(x,y)=(-y,x) and κ,D>0\kappa,D>0. Its stationary density is isotropic Gaussian π(x)=κ2πDe−κ∥x∥2/(2D)\pi(x)=\frac{\kappa}{2\pi D}e^{-\kappa\|x\|^2/(2D)} for any ω\omega, but J(x)=ωRx π(x)J(x)=\omega Rx\,\pi(x). Its divergence is zero because RxRx is tangent to circles and divergence-free. With ω=0\omega=0 there is detailed balance; with ω≠0\omega\ne0 mass circulates even though the density does not change. Time reversal reverses the current’s direction. See Pavliotis.

InteractiveStationary does not mean reversible

The background shows the same stationary density in every case. Arrows represent probability current, not drift or an individual path.

  • Stationary density
  • Current J

Model on the whole plane: dX = (−X + ωRX)dt + √2 dB, with R(x,y)=(−y,x). Density π(x,y)=e−(x²+y²)/2/(2π) does not depend on ω. Each cell color is proportional to π at its center; the box shows only [−3,3]².

J=bπ−∇π=ωR(x,y)π. Arrows share a scale for all ω values and are omitted if too small to draw. Although ∇·J=0 for every ω, only ω=0 has J=0 and detailed balance. Changing the sign of ω reverses circulation.

1.0
J en (1, 0)(0, 0.0965)
Maximum |J|0.0965
Stationary divergence0
Detailed balanceNo
Add a rotational component and compare density with current.

Feynman-Kac: solve a PDE with paths

For discount or potential r(t,x)r(t,x) and terminal payoff gg, the Feynman-Kac formula represents, under suitable existence, regularity and integrability assumptions,

u(t,x)=Et,x[e−∫tTr(s,Xs)dsg(XT)],∂tu+Lu−ru=0,u(T,x)=g(x).u(t,x)=E_{t,x}\left[e^{-\int_t^T r(s,X_s)ds}g(X_T)\right], \qquad \partial_tu+Lu-r u=0,\quad u(T,x)=g(x).

The proof applies Itô to the product of u(s,Xs)u(s,X_s) and the exponential factor: drift vanishes by the PDE and, if the stochastic integral is a true martingale, endpoint expectations agree. In a domain with exit, incorporate the boundary condition and stop the process.

The formula links path functionals and parabolic equations; Kac’s work studies distributions of Wiener functionals. For a statement with explicit regularity and growth assumptions, see the Stanford notes.

With standard Brownian motion, constant rr and g(x)=cos⁡(qx)g(x)=\cos(qx), Gaussian expectation gives u(t,x)=e−(r+q2/2)(T−t)cos⁡(qx)u(t,x)=e^{-(r+q^2/2)(T-t)}\cos(qx). This case allows comparison of finite differences, Monte Carlo and an exact solution. In finance the Black-Scholes PDE is a discounted backward equation under the appropriate pricing measure; physical drift is not simply replaced by a risk-free rate. The probability-flow ODE of diffusion models shares an SDE’s marginal evolution under its assumptions, although their paths differ.

Lab: conserving mass

On [−L,L][-L,L] with reflecting boundaries, divide space into cells. At each face approximate J=bp−D∂xpJ=bp-D\partial_xp with upwind drift and centered diffusion. Updating a cell by incoming minus outgoing flux makes all interior fluxes cancel when summed; at endpoints impose zero flux. The explicit step condition must keep coefficients nonnegative.

For an interior cell of width Δx\Delta x, the coefficient of its own density is 1−Δt[2D/Δx2+bi+1/2+/Δx+(−bi−1/2)+/Δx]1-\Delta t[2D/\Delta x^2+b_{i+1/2}^{+}/\Delta x+(-b_{i-1/2})^{+}/\Delta x]. A sufficient bound for all coefficients is Δt[2D/Δx2+2max⁡∣b∣/Δx]≤1\Delta t[2D/\Delta x^2+2\max|b|/\Delta x]\le1. It is sufficient, not necessary. Remaining neighboring coefficients are nonnegative and boundary fluxes are zero: thus the update conserves mass and preserves positivity in exact arithmetic.

We compare Euler for the same diffusion and reflect each step in the box. This discrete reflection approximates a reflected diffusion; it does not exactly reproduce what happens between nodes. Boundaries and time step matter. The initial histogram of both descriptions comes from the same particles.

[ ]Finite volumes and particles in a double wellBrowser
import numpy as np

rng=np.random.default_rng(2828)
L,D,n=2.5,.3,100
edges=np.linspace(-L,L,n+1)
dx=edges[1]-edges[0]
centers=(edges[:-1]+edges[1:])/2
faces=edges[1:-1]
drift=lambda x:x-x**3
potential=lambda x:(x*x-1)**2/4
dt=.001
assert dt*(2*D/dx**2+2*np.max(np.abs(drift(edges)))/dx)<1
m=4000
initial=np.where(rng.random(m)<.5,-.8,.8)+.1*rng.normal(size=m)

def reflect(x):
    z=np.mod(x+L,4*L)
    return -L+np.where(z<=2*L,z,4*L-z)

particles=reflect(initial)
density=np.histogram(particles,bins=edges)[0]/(m*dx)
initial_mass=density.sum()*dx
for _ in range(1000):
    v=drift(faces)
    J=v*np.where(v>=0,density[:-1],density[1:])-D*np.diff(density)/dx
    flux=np.r_[0.,J,0.]
    density-=dt*np.diff(flux)/dx
    particles=reflect(particles+drift(particles)*dt+np.sqrt(2*D*dt)*rng.normal(size=m))
hist=np.histogram(particles,bins=edges)[0]/(m*dx)
equilibrium=np.exp(-potential(centers)/D)
equilibrium/=equilibrium.sum()*dx
assert density.min()>-1e-12
print("masa inicial y final:",initial_mass,density.sum()*dx)
print("densidad mínima y distancia L1 al histograma:",density.min(),np.sum(np.abs(density-hist))*dx)
print("distancia L1 a Gibbs en t=1:",np.sum(np.abs(density-equilibrium))*dx)

The Gibbs density in the box has zero current and is normalized over that box. The initial state is not stationary: distance to Gibbs at a finite time need not be small. Distance to the histogram depends on sample size and both discretizations.

[ ]Stationary densities: double well and CIRBrowser
from scipy.stats import gamma
from scipy.integrate import quad

normalizer,_=quad(lambda x:np.exp(-potential(x)/D),-L,L)
print("doble pozo: normalización y densidad en cero:",
      normalizer,np.exp(-potential(0)/D)/normalizer)
kappa,theta,sigma=1.2,.05,.4
shape=2*kappa*theta/sigma**2
scale=sigma**2/(2*kappa)
cir=gamma(a=shape,scale=scale)
print("CIR: forma, escala, media teórica y P(X≤0,05):",
      shape,scale,cir.mean(),cir.cdf(.05))
assert np.isclose(cir.mean(),theta)

Lab: one expectation three ways

For the discounted heat problem use remaining time τ=T−t\tau=T-t. Crank-Nicolson averages the spatial operator between two dates and solves a tridiagonal system; at the box endpoints impose values of the known solution. This isolates interior numerical error, but for a problem without a known solution the boundary must also be justified or approximated. Finite-difference stencils and their errors are studied in more detail in simulation.

The Monte Carlo sample directly uses the exact Gaussian transition at the terminal date, so it has no time discretization error in this example. Compare its standard error with distance to the exact solution.

[ ]Feynman-Kac, finite differences and exact transitionBrowser
from scipy.linalg import solve_banded

T,r,q=1.,.3,1.1
grid=np.linspace(-5.,5.,101)
h=grid[1]-grid[0]
steps=200
dt=T/steps
alpha=.5*dt/h**2
u=np.cos(q*grid)
band=np.zeros((3,len(grid)-2))
band[0,1:]=-alpha/2
band[1,:]=1+alpha+r*dt/2
band[2,:-1]=-alpha/2
exact=lambda tau,x:np.exp(-(r+q*q/2)*tau)*np.cos(q*x)
for step in range(steps):
    tau=(step+1)*dt
    rhs=(1-alpha-r*dt/2)*u[1:-1]+alpha/2*(u[:-2]+u[2:])
    left,right=exact(tau,grid[0]),exact(tau,grid[-1])
    rhs[0]+=alpha/2*left
    rhs[-1]+=alpha/2*right
    u[1:-1]=solve_banded((1,1),band,rhs)
    u[0],u[-1]=left,right
index=np.argmin(abs(grid-.4))
x=grid[index]
sample=np.exp(-r*T)*np.cos(q*(x+np.sqrt(T)*rng.normal(size=30000)))
mc=sample.mean()
se=sample.std(ddof=1)/np.sqrt(len(sample))
truth=exact(T,x)
print("x, exacto, diferencias finitas, Monte Carlo y error estándar:",
      x,truth,u[index],mc,se)
print("errores absolutos de PDE y Monte Carlo:",
      abs(u[index]-truth),abs(mc-truth))
assert abs(u[index]-truth)<.002
assert abs(mc-truth)<5*se

The Monte Carlo interval concerns sampling for this exact transition. In a general SDE, discretizing the path and discount integral would add bias; reducing that bias and increasing the number of paths are different tasks.

Exercises

ProofFrom Itô to the backward equation
Prove: Let u be C¹ in time and C² in space, with sufficient integrability for the stochastic integral to be a martingale. Derive the PDE satisfied by u(t,x)=E[g(X_T) | X_t=x].
0
Apply Itô to u(s,Xₛ) between t and T and use the Markov property.

Step 1 of 3. What drift appears in d u(s,Xₛ)?

ProofCalculate the adjoint
Prove: In one dimension derive the Fokker-Planck equation for dX=b(X)dt+σ(X)dB assuming sufficient regularity and zero boundary terms.
0
Start with d/dt ∫f(x)p(t,x)dx = ∫Lf(x)p(t,x)dx and use smooth test functions.

Step 1 of 3. What is Lf?

ProofGibbs in a double well
Prove: For dX=−U′(X)dt+√(2D)dB, D>0, show π(x)=Z⁻¹e^(−U(x)/D) is stationary when Z is finite and boundary flow is zero.
0
First write the current J=−U′π−Dπ′.

Step 1 of 3. What is the derivative of π?

NumericTime to exit
Standard Brownian motion starts at x=0.5 inside (−1,1). What is its expected time to first exit?
QuizWhich variable evolves
Which pair of statements correctly distinguishes the two equations?
CodeFeynman-Kac with Euler and discounting
Implement feynman_kac_mc(sde,g,r,x,T,n=100,m=5000,seed=28). sde(t,x) returns drift and diffusion for an array of states; g(x) is vectorized and r(t,x) is vectorized instantaneous discounting. Use Euler with independent normals of variance dt and approximate the integral of r by the left endpoint. Return sample mean and standard error. Reject negative T, n<1 or m<2.
import numpy as np

def feynman_kac_mc(sde,g,r,x,T,n=100,m=5000,seed=28):
  pass
Shift+Enter to run
Key idea

The generator acts on state functions and its adjoint on densities. Dynkin connects exit and boundary problems; Feynman-Kac turns a discounted expectation into a backward equation when regularity and integrability assumptions hold.

[ ]Check the exit timeBrowser
print("tiempo medio desde x=0,5:",1-.5**2)