Bugfixes in math_utils.
[python_utils.git] / math_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """Mathematical helpers."""
6
7 import collections
8 import functools
9 import math
10 from heapq import heappop, heappush
11 from typing import Dict, List, Optional, Tuple
12
13 import dict_utils
14
15
16 class NumericPopulation(object):
17     """A numeric population with some statistics such as median, mean, pN,
18     stdev, etc...
19
20     >>> pop = NumericPopulation()
21     >>> pop.add_number(1)
22     >>> pop.add_number(10)
23     >>> pop.add_number(3)
24     >>> pop.get_median()
25     3
26     >>> pop.add_number(7)
27     >>> pop.add_number(5)
28     >>> pop.get_median()
29     5
30     >>> pop.get_mean()
31     5.2
32     >>> round(pop.get_stdev(), 2)
33     1.75
34     >>> pop.get_percentile(20)
35     3
36     >>> pop.get_percentile(60)
37     7
38     """
39
40     def __init__(self):
41         self.lowers, self.highers = [], []
42         self.aggregate = 0.0
43         self.sorted_copy: Optional[List[float]] = None
44
45     def add_number(self, number: float):
46         """Adds a number to the population.  Runtime complexity of this
47         operation is :math:`O(2 log_2 n)`"""
48
49         if not self.highers or number > self.highers[0]:
50             heappush(self.highers, number)
51         else:
52             heappush(self.lowers, -number)  # for lowers we need a max heap
53         self.aggregate += number
54         self._rebalance()
55
56     def _rebalance(self):
57         if len(self.lowers) - len(self.highers) > 1:
58             heappush(self.highers, -heappop(self.lowers))
59         elif len(self.highers) - len(self.lowers) > 1:
60             heappush(self.lowers, -heappop(self.highers))
61
62     def get_median(self) -> float:
63         """Returns the approximate median (p50) so far in O(1) time."""
64
65         if len(self.lowers) == len(self.highers):
66             return -self.lowers[0]
67         elif len(self.lowers) > len(self.highers):
68             return -self.lowers[0]
69         else:
70             return self.highers[0]
71
72     def get_mean(self) -> float:
73         """Returns the mean (arithmetic mean) so far in O(1) time."""
74
75         count = len(self.lowers) + len(self.highers)
76         return self.aggregate / count
77
78     def get_mode(self) -> Tuple[float, int]:
79         """Returns the mode (most common member in the population)
80         in O(n) time."""
81
82         count: Dict[float, int] = collections.defaultdict(int)
83         for n in self.lowers:
84             count[-n] += 1
85         for n in self.highers:
86             count[n] += 1
87         return dict_utils.item_with_max_value(count)
88
89     def get_stdev(self) -> float:
90         """Returns the stdev so far in O(n) time."""
91
92         mean = self.get_mean()
93         variance = 0.0
94         for n in self.lowers:
95             n = -n
96             variance += (n - mean) ** 2
97         for n in self.highers:
98             variance += (n - mean) ** 2
99         count = len(self.lowers) + len(self.highers)
100         return math.sqrt(variance) / count
101
102     def _create_sorted_copy_if_needed(self, count: int):
103         if not self.sorted_copy or count != len(self.sorted_copy):
104             self.sorted_copy = []
105             for x in self.lowers:
106                 self.sorted_copy.append(-x)
107             for x in self.highers:
108                 self.sorted_copy.append(x)
109             self.sorted_copy = sorted(self.sorted_copy)
110
111     def get_percentile(self, n: float) -> float:
112         """Returns the number at approximately pn% (i.e. the nth percentile)
113         of the distribution in O(n log n) time.  Not thread-safe;
114         does caching across multiple calls without an invocation to
115         add_number for perf reasons.
116         """
117         if n == 50:
118             return self.get_median()
119         count = len(self.lowers) + len(self.highers)
120         self._create_sorted_copy_if_needed(count)
121         assert self.sorted_copy
122         index = round(count * (n / 100.0))
123         index = max(0, index)
124         index = min(count - 1, index)
125         return self.sorted_copy[index]
126
127
128 def gcd_floats(a: float, b: float) -> float:
129     """Returns the greatest common divisor of a and b."""
130     if a < b:
131         return gcd_floats(b, a)
132
133     # base case
134     if abs(b) < 0.001:
135         return a
136     return gcd_floats(b, a - math.floor(a / b) * b)
137
138
139 def gcd_float_sequence(lst: List[float]) -> float:
140     """Returns the greatest common divisor of a list of floats."""
141     if len(lst) <= 0:
142         raise ValueError("Need at least one number")
143     elif len(lst) == 1:
144         return lst[0]
145     assert len(lst) >= 2
146     gcd = gcd_floats(lst[0], lst[1])
147     for i in range(2, len(lst)):
148         gcd = gcd_floats(gcd, lst[i])
149     return gcd
150
151
152 def truncate_float(n: float, decimals: int = 2):
153     """Truncate a float to a particular number of decimals.
154
155     >>> truncate_float(3.1415927, 3)
156     3.141
157
158     """
159     assert 0 < decimals < 10
160     multiplier = 10**decimals
161     return int(n * multiplier) / multiplier
162
163
164 def percentage_to_multiplier(percent: float) -> float:
165     """Given a percentage (e.g. 155%), return a factor needed to scale a
166     number by that percentage.
167
168     >>> percentage_to_multiplier(155)
169     2.55
170     >>> percentage_to_multiplier(45)
171     1.45
172     >>> percentage_to_multiplier(-25)
173     0.75
174     """
175     multiplier = percent / 100
176     multiplier += 1.0
177     return multiplier
178
179
180 def multiplier_to_percent(multiplier: float) -> float:
181     """Convert a multiplicative factor into a percent change.
182
183     >>> multiplier_to_percent(0.75)
184     -25.0
185     >>> multiplier_to_percent(1.0)
186     0.0
187     >>> multiplier_to_percent(1.99)
188     99.0
189     """
190     percent = multiplier
191     if percent > 0.0:
192         percent -= 1.0
193     else:
194         percent = 1.0 - percent
195     percent *= 100.0
196     return percent
197
198
199 @functools.lru_cache(maxsize=1024, typed=True)
200 def is_prime(n: int) -> bool:
201     """
202     Returns True if n is prime and False otherwise.  Obviously(?) very slow for
203     very large input numbers.
204
205     >>> is_prime(13)
206     True
207     >>> is_prime(22)
208     False
209     >>> is_prime(51602981)
210     True
211     """
212     if not isinstance(n, int):
213         raise TypeError("argument passed to is_prime is not of 'int' type")
214
215     # Corner cases
216     if n <= 1:
217         return False
218     if n <= 3:
219         return True
220
221     # This is checked so that we can skip middle five numbers in below
222     # loop
223     if n % 2 == 0 or n % 3 == 0:
224         return False
225
226     i = 5
227     while i * i <= n:
228         if n % i == 0 or n % (i + 2) == 0:
229             return False
230         i = i + 6
231     return True
232
233
234 if __name__ == '__main__':
235     import doctest
236
237     doctest.testmod()