Problem · Array
Handwritten Softmax
Learn this problemProblem statement
Given a nonempty double array logits, return its softmax probability array in the same order.
Let m be the maximum logit. For every index i, compute:
probability[i] = exp(logits[i] - m) / sum(exp(logits[j] - m))
Subtracting m is required for numerical stability and does not change the mathematical softmax. Implement the loops directly without a machine-learning or numerical-array library.
Function
softmax(logits: double[]) → double[]Examples
Example 1
logits = [1.0,2.0,3.0]return = [0.09003057317038046,0.24472847105479764,0.6652409557748218]After subtracting the maximum 3, normalize [exp(-2), exp(-1), 1] by their sum.
Example 2
logits = [1000.0,1000.0]return = [0.5,0.5]Equal logits have equal exponentials after maximum subtraction, so they split the probability mass evenly.
Example 3
logits = [5.0]return = [1.0]A one-element array has all of the probability mass at its only index.
Constraints
1 <= logits.length <= 200-1000 <= logits[i] <= 1000- Every logit is finite: no value is NaN or infinity.
- The result is compared element by element with absolute tolerance
1e-12.