Softmax Without Overflow

Activation FunctionsMedium+20 XP+15

Softmax Without Overflow

Softmax turns a vector of raw scores into a probability distribution — every entry lands in (0, 1) and the whole thing sums to 1.

softmax(x)ᵢ = exp(xᵢ) / Σⱼ exp(xⱼ)

Written exactly like that, it breaks. exp(1000) overflows to inf, and inf / inf is nan. The fix is a one-liner that every real implementation uses: subtract the maximum value from every entry first. Because the same constant cancels from numerator and denominator, the result is mathematically identical — but nothing ever gets exponentiated above exp(0) = 1.

Task: write softmax(x) for a list of numbers x, returning the probabilities rounded to 4 decimal places. It must survive inputs in the thousands.

Examples

x = [1.0, 2.0, 3.0]
returns [0.09, 0.2447, 0.6652]
x = [0.0, 0.0, 0.0, 0.0]
returns [0.25, 0.25, 0.25, 0.25]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run