Overflow-Safe Probability Normalization of Raw Scores
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Convert a list of real scores into a probability distribution via exponentiation and normalization, without overflow or division-by-zero for extreme input values.
Overflow-Safe Probability Normalization
You are given a list of real-valued scores. Turn it into a probability distribution in which larger scores receive larger probabilities. The probability assigned to position i is
p[i] = exp(scores[i]) / (exp(scores[0]) + exp(scores[1]) + ... + exp(scores[n-1]))
Evaluating this formula literally breaks down for extreme inputs. For large scores, exp exceeds the range of a double-precision float (in Python, math.exp(1000.0) raises an OverflowError; in other environments it yields inf, which leads to NaN after division). For very negative scores, every exp term can underflow to 0.0, producing a 0 / 0 division.
Write a function that returns the correct distribution for every valid input, including those extreme cases.
Requirements
- Return a list of floats the same length as the input, where entry
iis the probability forscores[i]. - The result must equal the mathematical definition above (to normal double-precision accuracy), not an approximation.
- Your function must never raise an overflow error and must never return
NaNorinffor inputs within the constraints. - A probability that is too small to represent in a double should come out as
0.0. - Equal scores must receive equal probabilities. A one-element input yields
[1.0].
Constraints
1 <= len(scores) <= 10^5-10^4 <= scores[i] <= 10^4- Values may be given as integers or floats.
Examples
Example 1
Input: scores_to_probabilities([1, 2, 3])
Output: [0.09003057317038046, 0.24472847105479764, 0.6652409557748218]
Example 2
Input: scores_to_probabilities([1000, 1000])
Output: [0.5, 0.5]
Hints
Hint 1
Adding or subtracting the same constant from every score leaves the final probabilities unchanged, because the constant's factor cancels between numerator and denominator.
Hint 2
Pick the constant so that the largest shifted score is exactly 0. Then every exponent argument is at most 0, so no term can overflow.
Hint 3
After the shift, the largest element contributes exactly 1 to the denominator, so the denominator is at least 1 and you never divide by zero, even when the other terms underflow.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The distribution is unchanged if the same constant C is subtracted from every score, since
exp(s_i - C) / sum_j exp(s_j - C) = exp(s_i) / sum_j exp(s_j)
because the factor exp(-C) appears in both the numerator and the denominator and cancels.
Choose C = max(scores). Then:
- Every shifted score is
<= 0, so everyexpvalue lies in(0, 1]. Overflow cannot happen. - The maximum element becomes exactly
0, so it contributes exactly1.0to the sum. The denominator is therefore at least1, and division by zero is impossible, even if all other terms underflow to0.0.
Steps:
- Find the maximum score.
- Compute
exp(score - maximum)for each score. - Add these values (using
math.fsumfor an accurately rounded sum over many terms of differing magnitude). - Divide each value by the total.
Why it is correct
The shift is an exact algebraic identity, so the result is the true distribution rather than an approximation. Terms that underflow to 0.0 correspond to true probabilities far below the smallest representable double, so 0.0 is the correctly rounded value. Ties at the maximum each contribute 1.0 and receive equal probabilities, and a single-element input gives exp(0) / 1 = 1.0. The naive formula also fails for very negative inputs (it gives 0 / 0), which the shift handles as well.
Complexity
- Time:
O(n)(a pass for the maximum, one for the exponentials, one for the sum, one for normalization). - Space:
O(n)for the weights and the output.
Reference solution
import math
from typing import List
def scores_to_probabilities(scores: List[float]) -> List[float]:
top = max(scores)
weights = [math.exp(s - top) for s in scores]
total = math.fsum(weights)
return [w / total for w in weights]