Advanced sampling and rare eventsLesson 65 of 76 · 8 min
Keep weights stable on a log scale
Normalise extreme log weights without numerical underflow.
Floating-point arithmetic has a finite range. Expanding very negative log weights can underflow, rounding them all to zero before their ratios are formed. Very large exponentials can overflow to infinity. Log weights record the logarithms of positive weights so ratios can be handled before exponentiation.
logsumexp(l) means log(sum(exp(l))). It computes this stably by subtracting the largest log value m first, then returning m+log(sum(exp(l−m))). For [-1001,-1000,-999], m=-999 leaves [-2,-1,0], whose exponentials are representable. Divide those exponentials by their sum: approximately [.090,.245,.665]. A common shift cancels from normalised weights.
The code uses exp(l−logsumexp(l)), the same normalisation in one expression. This repairs arithmetic, not poor target/proposal overlap. For an ordinary importance estimate with known normalising constant, preserve its original contribution scale. A self-normalised estimate instead divides weighted function values by total weight; the next lessons examine that different ratio estimator.
is log weight i, z is logsumexp of all log weights, and is its positive weight divided by the total. In code, dot multiplies corresponding entries and adds them, giving the weighted sum.
Should adding the same constant to every log weight change their normalised proportions?
Write a prediction (optional)
Constructed log-weight example
Select Run Python below with the code unchanged.
A saved draft is open. To run the published example, open Tools and select Restore example. Recover draft brings your code back.
Execution error
Technical error details
Your result
Published example output
This result comes from the original Python. Your runs appear above. Build environment ↗
Direct exponential sum: 0.0 Stable normalised weights: [0.090031 0.244728 0.665241] Weight sum: 1.0 Weighted average of [1,2,3]: 2.57521
Read the first result
The stable calculation recovers meaningful relative weights even though direct exponentials all become zero.
Try an edit
Replace [-1001.0, -1000.0, -999.0] with [-1000.0, -1000.0, -1000.0]. Select Run Python again. Compare Direct exponential sum, Stable normalised weights and Weighted average of [1,2,3]. What weights should a set of three equal inputs produce?
Scope. The demonstration concerns floating-point arithmetic on supplied weights, not validation of an underlying probability model.
Try a fresh case
Does stable log arithmetic ensure that importance sampling has explored every important region?
Need a hint?
Hint 1
Separate the values stored in memory from the states visited.
Hint 2
Ask whether a stabilised weight can represent a state never sampled.