3 # © Copyright 2021-2022, Scott Gasch
5 """Mathematical helpers."""
10 from heapq import heappop, heappush
11 from typing import Dict, List, Optional, Tuple
16 class NumericPopulation(object):
17 """A numeric population with some statistics such as median, mean, pN,
20 >>> pop = NumericPopulation()
22 >>> pop.add_number(10)
32 >>> round(pop.get_stdev(), 2)
34 >>> pop.get_percentile(20)
36 >>> pop.get_percentile(60)
41 self.lowers, self.highers = [], []
43 self.sorted_copy: Optional[List[float]] = None
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)`"""
49 if not self.highers or number > self.highers[0]:
50 heappush(self.highers, number)
52 heappush(self.lowers, -number) # for lowers we need a max heap
53 self.aggregate += number
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))
62 def get_median(self) -> float:
63 """Returns the approximate median (p50) so far in O(1) time."""
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]
70 return self.highers[0]
72 def get_mean(self) -> float:
73 """Returns the mean (arithmetic mean) so far in O(1) time."""
75 count = len(self.lowers) + len(self.highers)
76 return self.aggregate / count
78 def get_mode(self) -> Tuple[float, int]:
79 """Returns the mode (most common member in the population)
82 count: Dict[float, int] = collections.defaultdict(int)
85 for n in self.highers:
87 return dict_utils.item_with_max_value(count)
89 def get_stdev(self) -> float:
90 """Returns the stdev so far in O(n) time."""
92 mean = self.get_mean()
96 variance += (n - mean) ** 2
97 for n in self.highers:
98 variance += (n - mean) ** 2
99 count = len(self.lowers) + len(self.highers) - 1
100 return math.sqrt(variance) / count
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)
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.
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 assert 0 <= index < count
124 return self.sorted_copy[index]
127 def gcd_floats(a: float, b: float) -> float:
128 """Returns the greatest common divisor of a and b."""
130 return gcd_floats(b, a)
135 return gcd_floats(b, a - math.floor(a / b) * b)
138 def gcd_float_sequence(lst: List[float]) -> float:
139 """Returns the greatest common divisor of a list of floats."""
141 raise ValueError("Need at least one number")
145 gcd = gcd_floats(lst[0], lst[1])
146 for i in range(2, len(lst)):
147 gcd = gcd_floats(gcd, lst[i])
151 def truncate_float(n: float, decimals: int = 2):
152 """Truncate a float to a particular number of decimals.
154 >>> truncate_float(3.1415927, 3)
158 assert 0 < decimals < 10
159 multiplier = 10**decimals
160 return int(n * multiplier) / multiplier
163 def percentage_to_multiplier(percent: float) -> float:
164 """Given a percentage (e.g. 155%), return a factor needed to scale a
165 number by that percentage.
167 >>> percentage_to_multiplier(155)
169 >>> percentage_to_multiplier(45)
171 >>> percentage_to_multiplier(-25)
174 multiplier = percent / 100
179 def multiplier_to_percent(multiplier: float) -> float:
180 """Convert a multiplicative factor into a percent change.
182 >>> multiplier_to_percent(0.75)
184 >>> multiplier_to_percent(1.0)
186 >>> multiplier_to_percent(1.99)
193 percent = 1.0 - percent
198 @functools.lru_cache(maxsize=1024, typed=True)
199 def is_prime(n: int) -> bool:
201 Returns True if n is prime and False otherwise. Obviously(?) very slow for
202 very large input numbers.
208 >>> is_prime(51602981)
211 if not isinstance(n, int):
212 raise TypeError("argument passed to is_prime is not of 'int' type")
220 # This is checked so that we can skip middle five numbers in below
222 if n % 2 == 0 or n % 3 == 0:
227 if n % i == 0 or n % (i + 2) == 0:
233 if __name__ == '__main__':