Deriving the Normal Moment-Generating Function by Completing the Square
Original question
How can I calculate the moment generating function of a normally distributed random variable and use it to derive expectations?
For X∼N(μ,σ2), the moment generating function is MX(t)=exp(μt+σ2t2/2). Complete the square inside the normal-density integral to derive it. Differentiate at zero to obtain ordinary moments, or substitute a nonzero argument to evaluate an expectation such as E[eX].
Complete the square around a shifted normal mean
Let μ be the mean, σ2 the variance, and t the argument of the moment-generating function. The variable of integration x represents a possible value of X. For σ>0, write E[etX] using the normal density.
MX(t)=σ2π1∫−∞∞exp(tx−2σ2(x−μ)2)dx.
Only the linear coefficient in x changes when you multiply the density by etx. The coefficient is now μ/σ2+t. A normal kernel with mean μ+σ2t has that coefficient, and its quadratic coefficient remains −1/(2σ2). You can keep track of the constant by writing tx=t(x−μ)+tμ.
The constant μt+σ2t2/2 is independent of x, so its exponential comes outside the integral. What remains is the density of a normal with mean μ+σ2t and variance σ2, integrated over the whole real line. Its integral is one. When σ=0, X=μ almost surely and the formula reduces directly to eμt.
Use the formula to get moments
The normal tails allow differentiation under the expectation near zero. Each derivative brings down one factor of X, so MX′(0)=E[X] and MX′′(0)=E[X2]. Differentiating the closed form gives
For an exponential moment such as E[eX], evaluate MX(1) directly. It is a different calculation from taking a derivative at zero.
Three moments from one formula
Let X∼N(2,9). Its first moment is 2, its second raw moment is 22+9=13, and its exponential moment is E[eX]=MX(1)=e6.5. Exponentiating the mean alone would give e2, which misses the contribution from dispersion.
In a stochastic calculus exercise, suppose BT∼N(0,T) and define ZT=eσBT−σ2T/2. Using the normal moment generating function at argument σ gives
This example computes the three quantities for the normal variable in the exercise and checks the first derivative with a centred difference.
from math import exp
mu, variance = 2.0, 9.0defmgf(t):return exp(mu * t + variance * t**2 / 2)
h = 1e-5print("Mean by centred difference:", (mgf(h) - mgf(-h)) / (2 * h))
print("Second raw moment:", mu**2 + variance)
print("Exponential moment:", mgf(1))
Numerical differentiation is a useful check on an analytic result. If you try the second derivative numerically, a very small step can cause cancellation because both nearby function values are close to one.