Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
proposal: math/rand: add function for random bool #23804
I'd argue that it's worth doing. It's not solving a hard problem but it's making it easier to read. Similar to how sync.Waitgroup.Done() is an just an extra 1 line function but makes it more expressive to read for the programmer.
I don't have an opinion on this, but I have a small argument in favour.
The way the
Take for example the simple method Ian proposed above:
We call r.Intn(2), which checks that the argument fits an int32, and then calls r.Int31n(2), which checks that the argument is a power of two, and then calls r.Int31(), which calls r.Int63() and then shifts the result and cast it into an int32.
This is what the call stack looks like:
An implementation that directly calls the function that is the nearest to the generator:
So while it's true that it is easy to write an expression that correctly returns a random boolean, doing so in a way that is performant and does not result in a deep call stack is not as immediate as it looks.
All of those checks and conversions should be easy to inline and constant-fold away.
Whereas I agree that as defined this does not add much (except, maybe, avoid biases in known bad bits of the PRNG output), I would suggest considering adding a probability to that function:
while this has an obvious implementation (
This would be useful for e.g. sampling events and approximate counting. Obviously,