Random bool

181 views
Skip to first unread message

Jason Gade

unread,
May 4, 2026, 8:35:42 PM (8 days ago) May 4
to golang-nuts
math/rand and math/rand/V2 have functions that return various int and float types, but no function that returns a bool. While this would be very easy to implement on our own, I think it's an oversight for the packages.

rand.Bool() could represent a coin flip, which is a very common need in random value generation and modeling.

M

unread,
May 5, 2026, 11:06:43 PM (7 days ago) May 5
to golang-nuts
func (r *Rand) IntN(n int) int comes awfully close, with n=2.

Randall O'Reilly

unread,
May 6, 2026, 6:13:50 AM (7 days ago) May 6
to M, golang-nuts
Because Go does not automatically convert int to bool, having the bool return type is critical for simple conditional expressions. This is the version I use, giving a boolean with given probability:

func BoolP(p float64) bool {
return rand.Float64() < p
}

as in:

if BoolP(0.25) {
...
}

- Randy
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/e5cd69fa-3869-42f3-9823-dd1e2a361d8fn%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages