3 """Mathematical helpers."""
8 from heapq import heappop, heappush
9 from typing import Dict, List, Optional, Tuple
14 class NumericPopulation(object):
15 """A numeric population with some statistics such as median, mean, pN,
18 >>> pop = NumericPopulation()
20 >>> pop.add_number(10)
30 >>> round(pop.get_stdev(), 2)
32 >>> pop.get_percentile(20)
34 >>> pop.get_percentile(60)
40 self.lowers, self.highers = [], []
42 self.sorted_copy: Optional[List[float]] = None
44 def add_number(self, number: float):
47 if not self.highers or number > self.highers[0]:
48 heappush(self.highers, number)
50 heappush(self.lowers, -number) # for lowers we need a max heap
51 self.aggregate += number
55 if len(self.lowers) - len(self.highers) > 1:
56 heappush(self.highers, -heappop(self.lowers))
57 elif len(self.highers) - len(self.lowers) > 1:
58 heappush(self.lowers, -heappop(self.highers))
60 def get_median(self) -> float:
61 """Returns the approximate median (p50) so far in O(1) time."""
63 if len(self.lowers) == len(self.highers):
64 return -self.lowers[0]
65 elif len(self.lowers) > len(self.highers):
66 return -self.lowers[0]
68 return self.highers[0]
70 def get_mean(self) -> float:
71 """Returns the mean (arithmetic mean) so far in O(1) time."""
73 count = len(self.lowers) + len(self.highers)
74 return self.aggregate / count
76 def get_mode(self) -> Tuple[float, int]:
77 count: Dict[float, int] = collections.defaultdict(int)
80 for n in self.highers:
82 return dict_utils.item_with_max_value(count)
84 def get_stdev(self) -> float:
85 """Returns the stdev so far in O(n) time."""
87 mean = self.get_mean()
91 variance += (n - mean) ** 2
92 for n in self.highers:
93 variance += (n - mean) ** 2
94 count = len(self.lowers) + len(self.highers) - 1
95 return math.sqrt(variance) / count
97 def get_percentile(self, n: float) -> float:
98 """Returns the number at approximately pn% (i.e. the nth percentile)
99 of the distribution in O(n log n) time (expensive, requires a
100 complete sort). Not thread safe. Caching does across
101 multiple calls without an invocation to add_number.
105 return self.get_median()
106 count = len(self.lowers) + len(self.highers)
107 if self.sorted_copy is not None:
108 if count == len(self.sorted_copy):
109 index = round(count * (n / 100.0))
110 assert 0 <= index < count
111 return self.sorted_copy[index]
112 self.sorted_copy = [-x for x in self.lowers]
113 for x in self.highers:
114 self.sorted_copy.append(x)
115 self.sorted_copy = sorted(self.sorted_copy)
116 index = round(count * (n / 100.0))
117 assert 0 <= index < count
118 return self.sorted_copy[index]
121 def gcd_floats(a: float, b: float) -> float:
123 return gcd_floats(b, a)
128 return gcd_floats(b, a - math.floor(a / b) * b)
131 def gcd_float_sequence(lst: List[float]) -> float:
133 raise ValueError("Need at least one number")
137 gcd = gcd_floats(lst[0], lst[1])
138 for i in range(2, len(lst)):
139 gcd = gcd_floats(gcd, lst[i])
143 def truncate_float(n: float, decimals: int = 2):
145 Truncate a float to a particular number of decimals.
147 >>> truncate_float(3.1415927, 3)
151 assert 0 < decimals < 10
152 multiplier = 10**decimals
153 return int(n * multiplier) / multiplier
156 def percentage_to_multiplier(percent: float) -> float:
157 """Given a percentage (e.g. 155%), return a factor needed to scale a
158 number by that percentage.
160 >>> percentage_to_multiplier(155)
162 >>> percentage_to_multiplier(45)
164 >>> percentage_to_multiplier(-25)
168 multiplier = percent / 100
173 def multiplier_to_percent(multiplier: float) -> float:
174 """Convert a multiplicative factor into a percent change.
176 >>> multiplier_to_percent(0.75)
178 >>> multiplier_to_percent(1.0)
180 >>> multiplier_to_percent(1.99)
188 percent = 1.0 - percent
193 @functools.lru_cache(maxsize=1024, typed=True)
194 def is_prime(n: int) -> bool:
196 Returns True if n is prime and False otherwise. Obviously(?) very slow for
197 very large input numbers.
203 >>> is_prime(51602981)
207 if not isinstance(n, int):
208 raise TypeError("argument passed to is_prime is not of 'int' type")
216 # This is checked so that we can skip middle five numbers in below
218 if n % 2 == 0 or n % 3 == 0:
223 if n % i == 0 or n % (i + 2) == 0:
229 if __name__ == '__main__':