Skip to content

Commit

Permalink
add population.entropy()
Browse files Browse the repository at this point in the history
  • Loading branch information
HighDiceRoller committed Oct 31, 2023
1 parent 671c5a8 commit 41e4208
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/icepool/population/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,16 @@ def excess_kurtosis(
self: 'Population[numbers.Rational] | Population[float]') -> float:
return self.standardized_moment(4) - 3.0

def entropy(self, base: float = 2.0) -> float:
"""The entropy of a random sample from this population.
Args:
base: The logarithm base to use. Default is 2.0, which gives the
entropy in bits.
"""
return -sum(
p * math.log(p, base) for p in self.probabilities() if p > 0.0)

# Joint statistics.

class _Marginals(Sequence):
Expand Down
5 changes: 5 additions & 0 deletions tests/statistics_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import icepool
import pytest

from icepool import Die
from fractions import Fraction


Expand Down Expand Up @@ -41,3 +42,7 @@ def test_min_quantile():
def test_max_quantile():
assert icepool.d6.quantile_low(100) == 6
assert icepool.d6.quantile_high(100) == 6


def test_entropy_with_zeros():
assert Die({1: 1, 2: 0, 3: 1}).entropy() == 1.0

0 comments on commit 41e4208

Please sign in to comment.