Created
January 20, 2020 13:03
-
-
Save ellimilial/c443a91a65d071ddcf4069052ddec122 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 convert it to a 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