starlib
starlib copied to clipboard
Implement a `random` module
What feature or capability would you like?
It would be nice to be able to generate random numbers.
Do you have a proposed solution?
Implement a random module that uses math/rand under the hood.
Have you considered any alternative solutions or workarounds?
From @betterengineering:
def random(seed):
"""
Returns a random number and the new seed value.
Starlark is meant to be deterministic, so anything that made the language non-deterministic (such as random number
generators) was removed. This is a Python implementation of a linear congruential generator I found here:
http://www.cs.wm.edu/~va/software/park/park.html
"""
modulus = 2147483648
multiplier = 48271
q = modulus / multiplier
r = modulus % multiplier
t = multiplier * (seed % q) - r * (seed / q);
if t > 0:
seed = t
else:
seed = t + modulus
return float(seed / modulus), seed
I agree having a random module would be nice. Not everyone is building with pseudo-determinism as a hard constraint. That said we should include a few changes to make access to the random package opt-in by default. I think adding a random package merits exporting a second top-level loader (or at least a configurable top-level loader) that determines weather the random package is available.
The second thing I'd expect from such a package would be an explicit set of controls within the go runtime to wrap and control any seed values within the starlark runtime
edit: hit submit too soon!