KL Divergence
Compute the Kullback-Leibler divergence between two discrete probability distributions.
where and are probability distributions over the same set of events.
By convention, if , the term contributes 0 to the sum (since ). If but , the divergence is infinity.
Return the KL divergence rounded to 4 decimal places. Return float('inf') if undefined.
Example
p = [0.4, 0.6] q = [0.5, 0.5]
0.0201
pandqare two probability distributions over the same two events: is the "true" distribution and is the uniform approximation being compared against it.- Each event contributes , weighted by how likely it is under .
- Event 1: the ratio is , and . It is negative because puts more mass here than does.
- Event 2: the ratio is , and .
- Summing: , which rounded to 4 decimal places is
0.0201. - Notice the total is small but positive: individual terms can be negative, yet the sum is never below 0, and it is exactly 0 only when . It is also not symmetric: swapping the roles of and gives , not .
Constraints
- p, q: lists of probabilities (same length, sum to 1)
- Use natural log
- Return float rounded to 4 decimal places
- Return float('inf') if P(i) > 0 and Q(i) = 0