Using random
The random module can be used with in_str as its seed, and when solving problems related to both thread safety and continuity.
However, the problem associated with cross algorithmic reproduction is a problem.
import random def str_to_probability(in_str): """Return a reproducible uniformly random float in the interval [0, 1) for the given seed.""" return random.Random(in_str).random() >>> str_to_probability('a3b2Foobar') 0.4662507245848473
Use hash
The cryptographic hash is supposedly uniformly distributed by an integer in the range [0, MAX_HASH]. Accordingly, it can be scaled to a floating point number in the range [0, 1) by dividing it by MAX_HASH + 1.
import hashlib Hash = hashlib.sha512 MAX_HASH_PLUS_ONE = 2**(Hash().digest_size * 8) def str_to_probability(in_str): """Return a reproducible uniformly random float in the interval [0, 1) for the given string.""" seed = in_str.encode() hash_digest = Hash(seed).digest() hash_int = int.from_bytes(hash_digest, 'big')
Notes:
- The built-in
hash method should not be used, since it can store distribution input, for example. with hash(123) . Alternatively, it can return values ββthat are different when restarting Python, for example. with hash('123') . - Using modulo is not required.
ABB
source share