Coverage for src/extratools_core/mathtools.py: 0%

9 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-07 08:29 -0700

1from collections import Counter 

2from collections.abc import Iterable 

3from math import inf, log2 

4 

5 

6def safediv(a: float, b: float) -> float: 

7 """ 

8 Safely divide float even when by 0, by returning infinity with proper sign. 

9 

10 Parameters 

11 ---------- 

12 a : float 

13 b : float 

14 

15 Returns 

16 ------- 

17 float 

18 Result of `a / b` 

19 """ 

20 

21 return inf * a if b == 0 else a / b 

22 

23 

24def entropy[T](data: Iterable[T]) -> float: 

25 """ 

26 Compute the entropy of data (as collection of items). 

27 

28 Parameters 

29 ---------- 

30 data : float 

31 Collection (as `Iterable`) of items 

32 

33 Returns 

34 ------- 

35 float 

36 Value of entropy 

37 """ 

38 

39 counter: Counter[T] = Counter(data) 

40 total: int = sum(counter.values()) 

41 

42 return -sum( 

43 p * log2(p) 

44 for p in ( 

45 curr / total 

46 for curr in counter.values() 

47 ) 

48 )