PIXELBANKv9.1.0
Menu

Compute the Kullback-Leibler divergence between two discrete probability distributions.

DKL(P∥Q)=∑iP(i)ln⁡P(i)Q(i)D_{KL}(P \| Q) = \sum_{i} P(i) \ln\frac{P(i)}{Q(i)}

where PP and QQ are probability distributions over the same set of events.

By convention, if P(i)=0P(i) = 0, the term contributes 0 to the sum (since 0ln⁡0=00 \ln 0 = 0). If P(i)>0P(i) > 0 but Q(i)=0Q(i) = 0, the divergence is infinity.

Return the KL divergence rounded to 4 decimal places. Return float('inf') if undefined.

Example:

Input:
p = [0.4, 0.6]
q = [0.5, 0.5]
Output:
0.0201
Reasoning:
  • The probability distributions are given as P=[0.4,0.6]P = [0.4, 0.6] and Q=[0.5,0.5]Q = [0.5, 0.5].
  • We calculate the KL divergence using the formula: DKL(P∥Q)=0.4ln⁡0.40.5+0.6ln⁡0.60.5D_{KL}(P \| Q) = 0.4 \ln\frac{0.4}{0.5} + 0.6 \ln\frac{0.6}{0.5}.
  • Evaluating the expression: DKL(P∥Q)=0.4ln⁡(0.8)+0.6ln⁡(1.2)D_{KL}(P \| Q) = 0.4 \ln(0.8) + 0.6 \ln(1.2), which is approximately 0.4⋅(−0.223)+0.6⋅0.1820.4 \cdot (-0.223) + 0.6 \cdot 0.182.
  • The final result is approximately −0.089+0.109=0.020-0.089 + 0.109 = 0.020, rounded to 4 decimal places: 0.02010.0201.

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
🔒

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.

solution.py

Test Results

0/0
Run code to see test results.
KL Divergence - Medium | PixelBank