KL Divergence: How Far Q Strays From P

Loss FunctionsMedium+10 XP+10

KL Divergence: How Far Q Strays From P

KL divergence measures how much one probability distribution differs from another — how many extra nats you'd waste encoding data from p using a code built for q instead.

DKL(P∥Q)=∑ipilog⁡piqiD_{KL}(P \| Q) = \sum_i p_i \log \frac{p_i}{q_i}DKL​(P∥Q)=i∑​pi​logqi​pi​​

Task: write kl_divergence(p, q) using the natural log, rounded to 4 decimal places.

  • Both p and q are valid probability distributions — positive values summing to 1.
  • kl_divergence(p, p) is always 0: a distribution needs no extra bits to describe itself.

Examples

p = [0.4, 0.6]
q = [0.5, 0.5]
returns 0.0201
p = [0.1, 0.2, 0.7]
q = [0.2, 0.2, 0.6]
returns 0.0386

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