Entropy measures the uncertainty or "surprise" of a probability distribution. For a discrete policy π over a set of actions A, the entropy is defined as:
H(π)=−a∈A∑π(a)logπ(a)
A deterministic policy (one action has probability 1, others 0) has zero entropy, meaning no exploration is needed. A uniform policy over n actions has maximum entropy logn, representing maximal uncertainty. In policy gradient methods, adding an entropy bonus to the objective function encourages the agent to keep exploring rather than collapsing to a greedy policy too early.
The term π(a)logπ(a) is well-behaved in the limit: as π(a)→0+, the product π(a)logπ(a)→0. This is a standard result from calculus (L'Hôpital's rule or the fact that xlogx→0 as x→0+). Therefore, actions with zero probability contribute nothing to the sum, and we should explicitly handle them to avoid computing log(0)=−∞.
In practice, policies are often represented as probability vectors (e.g., from a softmax output). The entropy is computed over this vector using the natural logarithm (ln), not log base 2 or base 10.
2. Algorithm Approach
This is a straightforward element-wise computation over a probability vector:
Iterate over each action's probability π(a).
If π(a)>0, compute π(a)⋅ln(π(a)) and accumulate.
If π(a)=0, skip (contribution is 0).
Return the negative of the accumulated sum.
The key insight is that the formula involves a sum of products, so you need a single pass over the vector with a running total. No sorting, no recursion, no data structures beyond a scalar accumulator.
3. Step-by-Step Strategy
PRO
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
PRO
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.