Skip to content

Instantly share code, notes, and snippets.

@ellimilial
Created January 20, 2020 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ellimilial/c443a91a65d071ddcf4069052ddec122 to your computer and use it in GitHub Desktop.
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().
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