#!/usr/bin/env python3
+# © Copyright 2021-2022, Scott Gasch
+
"""Mathematical helpers."""
import collections
3
>>> pop.get_percentile(60)
7
-
"""
def __init__(self):
self.sorted_copy: Optional[List[float]] = None
def add_number(self, number: float):
- """O(2 log2 n)"""
+ """Adds a number to the population. Runtime complexity of this
+ operation is :math:`O(2 log_2 n)`"""
if not self.highers or number > self.highers[0]:
heappush(self.highers, number)
return self.aggregate / count
def get_mode(self) -> Tuple[float, int]:
+ """Returns the mode (most common member in the population)
+ in O(n) time."""
+
count: Dict[float, int] = collections.defaultdict(int)
for n in self.lowers:
count[-n] += 1
def get_percentile(self, n: float) -> float:
"""Returns the number at approximately pn% (i.e. the nth percentile)
- of the distribution in O(n log n) time (expensive, requires a
- complete sort). Not thread safe. Caching does across
- multiple calls without an invocation to add_number.
-
+ of the distribution in O(n log n) time. Not thread-safe;
+ does caching across multiple calls without an invocation to
+ add_number for perf reasons.
"""
if n == 50:
return self.get_median()
def gcd_floats(a: float, b: float) -> float:
+ """Returns the greatest common divisor of a and b."""
if a < b:
return gcd_floats(b, a)
def gcd_float_sequence(lst: List[float]) -> float:
+ """Returns the greatest common divisor of a list of floats."""
if len(lst) <= 0:
raise ValueError("Need at least one number")
elif len(lst) == 1:
def truncate_float(n: float, decimals: int = 2):
- """
- Truncate a float to a particular number of decimals.
+ """Truncate a float to a particular number of decimals.
>>> truncate_float(3.1415927, 3)
3.141
1.45
>>> percentage_to_multiplier(-25)
0.75
-
"""
multiplier = percent / 100
multiplier += 1.0
0.0
>>> multiplier_to_percent(1.99)
99.0
-
"""
percent = multiplier
if percent > 0.0:
False
>>> is_prime(51602981)
True
-
"""
if not isinstance(n, int):
raise TypeError("argument passed to is_prime is not of 'int' type")