A robot localization replay may assign weights to several candidate states. If those weights come from products of many small terms, their ordinary floating-point representations can round to zero even when their ratios are meaningful. Keeping the logarithms until normalization helps preserve the relative weights. A different case occurs when the calculation assigned zero weight to every candidate. Then there is no positive weight to normalize.

This example uses invented scores for three candidates and was checked with NumPy 2.5.2. It tests a numerical step that can be part of a particle filter. It does not test a localization system, demonstrate a sensor model, or dictate how a robot should respond when localization fails.

Represent what the model assigned

Use natural logarithms of unnormalized weights. The first two scores are -1000 and -1001. The second is one log unit lower than the first, so its weight is the first weight multiplied by the exponential of -1. The third score is negative infinity, representing an explicitly zero weight. Those are separate cases even though exponentiating the scores directly produces three zeros in the fixture.

import numpy as np

log_w = np.array([-1000., -1001., -np.inf])

assert np.exp(log_w).tolist() == [0., 0., 0.]

The two finite scores describe positive values that are too small to represent in the chosen linear format. The infinite negative score denotes a zero from the model. Once the direct conversion has discarded the difference, a later normalization sees a zero sum without knowing which case produced it.

Calculate the total in log space

NumPy's logaddexp combines two log weights by calculating the logarithm of the sum of their corresponding linear weights. Its reduce method extends this operation across a vector. In the fixture, the log of the total is approximately -999.6867383124818, even though exponentiating that result in float64 would give zero.

log_total = np.logaddexp.reduce(log_w)

assert np.isclose(log_total, -999.6867383124818)

For a normalized log weight, subtract the log total from the candidate's log weight. Exponentiating the difference yields the ratio to the total, so the largest candidate becomes approximately 0.7311 and the second approximately 0.2689. The explicitly excluded candidate receives zero.

A common shift of all the finite log weights leaves these ratios unchanged. The following implementation first shifts by the largest finite score. This makes the maximum score zero and keeps the normalization arithmetic on relative scores. It also checks whether the input has any positive mass before performing subtraction.

def normalize(log_weights):

if (log_weights.ndim != 1

or np.isnan(log_weights).any()

or np.isposinf(log_weights).any()):

raise ValueError("Expected finite log weights or negative infinity")

if not np.isfinite(log_weights).any():

raise ValueError("No positive weight")

centered = log_weights - np.max(log_weights)

return np.exp(centered - np.logaddexp.reduce(centered))

weights = normalize(log_w)

assert np.allclose(weights, [0.73105858, 0.26894142, 0.])

assert np.isclose(weights.sum(), 1.)

assert np.allclose(normalize(log_w - 100.), weights)

This contract treats positive infinity and NaN as invalid input and permits negative infinity as a zero. A finite log weight can be above zero when weights are unnormalized. The function therefore does not reject finite positive scores. For comparisons that need very small ratios, retain the normalized log weights because converting even those relative values to linear form can still underflow.

Handle a batch with no positive weight

When every log weight is negative infinity, the log total is negative infinity. Subtracting it from every entry would involve subtracting an infinity from itself. Returning equal weights would instead assert a weighting choice that the input did not provide. The example reports this condition as an error. A real pipeline can decide whether to preserve a prior distribution, reject the update, or enter a separately defined recovery procedure. The normalization function should make the condition visible to whatever owns that decision.

An empty vector is also rejected. When several independent filters are processed in an array, reduce along the particle axis for each filter and check each slice individually. Pooling candidates from unrelated filters changes both their denominators and the interpretation of the results. Save the candidate IDs so a weight stays attached to the state that produced it, including any state explicitly assigned zero.

For example, if the input has one row per replay and one column per candidate, an axis of one selects a total per replay. In a batch already checked to contain a finite score in each row, keeping the reduced dimension allows that row's total to broadcast across its own candidates.

checked_batch = np.stack([log_w, log_w - 100.])

row_totals = np.logaddexp.reduce(

checked_batch, axis=1, keepdims=True

)

row_weights = np.exp(checked_batch - row_totals)

assert np.allclose(row_weights, np.stack([weights, weights]))

Apply the input checks before using this shorter batch calculation.

Verify ratios and input policy

A regression test can compare the sum against one within a stated tolerance after normalization. It should also verify the order of the two positive weights and the exact zero for the excluded candidate. Try a common shift of the log values and confirm the ratios stay the same. Add empty input, all negative infinities, and invalid nonfinite values to test the conditions the application treats separately.

Normalization reproduces the ratios implied by the supplied scores. A normalized vector alone cannot verify that the scores came from the intended observations or that the candidates cover the actual state. Keep the log scores, their measurement context, and any exclusion reasons together so a replay can explain where each weight came from.

A second test can compare normalized weights from independent batches while preserving candidate order.

Sources checked November 28, 2026

NumPy, numpy.logaddexp

https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html

NumPy, numpy.ufunc.reduce

https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html

Illustration. AI-generated concept of log weights converted to a normalized set of relative weights.