New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: math/rand/v2: add function for random bool #23804
Comments
Change https://golang.org/cl/93517 mentions this issue: |
How about |
Yes I believe it is worth it. |
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. |
If you're used to |
Leaving this for math/rand v2 discussions. Please just use r.Intn(2) == 0 for now. |
/cc @josharian too |
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, |
I want to be able to call
rand.Bool()
and receive a pseudo-random bool when I importmath/random
The text was updated successfully, but these errors were encountered: