Created
October 15, 2020 11:58
-
-
Save fridex/3794b9cbb35d1b8f523a94ee9d86b8e4 to your computer and use it in GitHub Desktop.
Termial random using CPython extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# pip install termial-random | |
from termial_random import random as termial_random | |
from termial_random import seed as termial_seed | |
import math | |
import os | |
import random | |
import sys | |
import timeit | |
_ROUNDS = int(os.getenv("TERMIAL_DEFAULT_ROUNDS", 3)) | |
_ITERATIONS = int(os.getenv("TERMIAL_ITERATIONS", 1000000)) | |
_N = int(os.getenv("TERMIAL_N", 10000)) | |
def random_termial_v0(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
termial_of_n = ((n * n) + n) >> 1 | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def random_termial_v1(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
termial_of_n = ((n ** 2) + n) >> 1 | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def random_termial_v2(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
if n % 2: # or n & 1 | |
# odd numbers | |
nearest = n + 1 | |
termial_of_n = ((1 + nearest) * (nearest / 2)) - nearest | |
else: | |
termial_of_n = (1 + n) * (n / 2) | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def random_termial_v3(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
addition = (n * (n & 1)) | |
nearest = n + addition | |
termial_of_n = ((1 + nearest) * (nearest >> 1)) - addition | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def main(): | |
print("n = ", _N) | |
print("rounds = ", _ROUNDS) | |
print("iterations = ", _ITERATIONS) | |
print() | |
termial_seed(100) | |
for i in range(_ROUNDS): | |
print(f">>> Round {i}") | |
for func in ("termial_random", "random_termial_v0", "random_termial_v1", "random_termial_v2", "random_termial_v3"): | |
print( | |
"\t", | |
func, | |
": ", | |
timeit.timeit( | |
f"{func}({_N})", | |
number=_ITERATIONS, | |
globals=globals(), | |
), | |
) | |
__name__ == "__main__" and main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: