3 """Mathematical helpers."""
7 from heapq import heappop, heappush
8 from typing import List, Optional
11 class NumericPopulation(object):
12 """A running median computer.
14 >>> pop = NumericPopulation()
16 >>> pop.add_number(10)
26 >>> round(pop.get_stdev(), 2)
28 >>> pop.get_percentile(20)
30 >>> pop.get_percentile(60)
35 self.lowers, self.highers = [], []
37 self.sorted_copy: Optional[List[float]] = None
39 def add_number(self, number: float):
42 if not self.highers or number > self.highers[0]:
43 heappush(self.highers, number)
45 heappush(self.lowers, -number) # for lowers we need a max heap
46 self.aggregate += number
50 if len(self.lowers) - len(self.highers) > 1:
51 heappush(self.highers, -heappop(self.lowers))
52 elif len(self.highers) - len(self.lowers) > 1:
53 heappush(self.lowers, -heappop(self.highers))
55 def get_median(self) -> float:
56 """Returns the approximate median (p50) so far in O(1) time."""
58 if len(self.lowers) == len(self.highers):
59 return -self.lowers[0]
60 elif len(self.lowers) > len(self.highers):
61 return -self.lowers[0]
63 return self.highers[0]
65 def get_mean(self) -> float:
66 """Returns the mean (arithmetic mean) so far in O(1) time."""
68 count = len(self.lowers) + len(self.highers)
69 return self.aggregate / count
71 def get_stdev(self) -> float:
72 """Returns the stdev so far in O(n) time."""
74 mean = self.get_mean()
78 variance += (n - mean) ** 2
79 for n in self.highers:
80 variance += (n - mean) ** 2
81 return math.sqrt(variance)
83 def get_percentile(self, n: float) -> float:
84 """Returns the number at approximately pn% (i.e. the nth percentile)
85 of the distribution in O(n log n) time (expensive, requires a
86 complete sort). Not thread safe. Caching does across
87 multiple calls without an invocation to add_number.
91 return self.get_median()
92 count = len(self.lowers) + len(self.highers)
93 if self.sorted_copy is not None:
94 if count == len(self.sorted_copy):
95 index = round(count * (n / 100.0))
96 assert 0 <= index < count
97 return self.sorted_copy[index]
98 self.sorted_copy = [-x for x in self.lowers]
99 for x in self.highers:
100 self.sorted_copy.append(x)
101 self.sorted_copy = sorted(self.sorted_copy)
102 index = round(count * (n / 100.0))
103 assert 0 <= index < count
104 return self.sorted_copy[index]
107 def gcd_floats(a: float, b: float) -> float:
109 return gcd_floats(b, a)
114 return gcd_floats(b, a - math.floor(a / b) * b)
117 def gcd_float_sequence(lst: List[float]) -> float:
119 raise ValueError("Need at least one number")
123 gcd = gcd_floats(lst[0], lst[1])
124 for i in range(2, len(lst)):
125 gcd = gcd_floats(gcd, lst[i])
129 def truncate_float(n: float, decimals: int = 2):
131 Truncate a float to a particular number of decimals.
133 >>> truncate_float(3.1415927, 3)
137 assert 0 < decimals < 10
138 multiplier = 10**decimals
139 return int(n * multiplier) / multiplier
142 def percentage_to_multiplier(percent: float) -> float:
143 """Given a percentage (e.g. 155%), return a factor needed to scale a
144 number by that percentage.
146 >>> percentage_to_multiplier(155)
148 >>> percentage_to_multiplier(45)
150 >>> percentage_to_multiplier(-25)
154 multiplier = percent / 100
159 def multiplier_to_percent(multiplier: float) -> float:
160 """Convert a multiplicative factor into a percent change.
162 >>> multiplier_to_percent(0.75)
164 >>> multiplier_to_percent(1.0)
166 >>> multiplier_to_percent(1.99)
174 percent = 1.0 - percent
179 @functools.lru_cache(maxsize=1024, typed=True)
180 def is_prime(n: int) -> bool:
182 Returns True if n is prime and False otherwise. Obviously(?) very slow for
183 very large input numbers.
189 >>> is_prime(51602981)
193 if not isinstance(n, int):
194 raise TypeError("argument passed to is_prime is not of 'int' type")
202 # This is checked so that we can skip middle five numbers in below
204 if n % 2 == 0 or n % 3 == 0:
209 if n % i == 0 or n % (i + 2) == 0:
215 if __name__ == '__main__':