[Python-ideas] random.boolean or bernoulli

Stefan Behnel stefan_ml at behnel.de
Thu Apr 21 05:49:01 CEST 2011


Erich Blume, 20.04.2011 23:37:
> I am yet a novice python user, and not a strong statistician to boot,
> but I had an idea about how to enhance the 'random' module with one or
> two new functions for generating boolean values instead of
> floating-point values.
>
> This idea has a lot of flexibility in how it might be implemented, but
> I propose two new functions for the random module that might be
> implemented in python as follows
>
> def boolean():
>      return choice((True,False))

I like this one. It reads well in code:

     if random.boolean():
         ...

It reads less well with a from-import:

     if boolean():
         ...

But that's just a matter of renaming while importing it:

     from random import boolean as random_choice

     if random_choice():
         ...


> def bernoulli(p):
>      return random()<= p

This seems less obvious:

     if random.bernoulli(0.5):
         ...

Who's Random Bernoulli anyway?

Stefan




More information about the Python-ideas mailing list