Last active
January 21, 2020 09:29
-
-
Save ellimilial/86a04428591a3fb39e31738c65b5be60 to your computer and use it in GitHub Desktop.
Convert string to a float in range range [0.0, 1.0), similar to random().
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
import hashlib | |
def string_to_deterministic_float(s: str) -> float: | |
""" | |
Given a string, deterministically map it to a uniformly sampled float in range [0.0, 1.0). | |
""" | |
b = bytes(s, encoding='utf-8') | |
h_dig = hashlib.sha256(b).hexdigest() | |
return int(h_dig, base=16) / 16 ** len(h_dig) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment