Obtener un booleano aleatorio en python?


Estoy buscando la mejor manera (rápida y elegante) de obtener un booleano aleatorio en python (lanzar una moneda).

Por el momento estoy usando random.randint(0, 1) o random.getrandbits(1).

¿Hay mejores opciones de las que no soy consciente?

 158
Author: Mark Amery, 2011-07-26

7 answers

La respuesta de Adán es bastante rápida, pero encontré que random.getrandbits(1) es bastante más rápida. Si realmente quieres un booleano en lugar de un largo entonces

bool(random.getrandbits(1))

Sigue siendo aproximadamente el doble de rápido que random.choice([True, False])

Ambas soluciones necesitan import random

Si la velocidad máxima no es la prioridad entonces random.choice definitivamente lee mejor

$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))" 
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop  # not takes about 20us of this

Agregó esto después de ver la respuesta de @ Pavel

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop
 232
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 14:44:21
random.choice([True, False])

También funcionaría.

 132
Author: Adam Vandenberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-26 02:48:37

Encontró un método más rápido:

$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random import random" "random() > 0.5"
10000000 loops, best of 3: 0.0579 usec per loop
 30
Author: Pavel Radchenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 21:04:02

Si quieres generar un número de booleanos aleatorios puedes usar el módulo aleatorio de numpy. De la documentación

np.random.randint(2, size=10)

Devolverá 10 enteros uniformes aleatorios en el intervalo abierto [0,2). La palabra clave size especifica el número de valores a generar.

 5
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-07 22:39:50

Me gusta

 np.random.rand() > .5
 4
Author: Maarten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-22 08:22:48

Tenía curiosidad en cuanto a cómo la velocidad de la respuesta numpy se realizó contra las otras respuestas, ya que esto se dejó fuera de las comparaciones. Para generar un bool aleatorio esto es mucho más lento, pero si quieres generar muchos, esto se vuelve mucho más rápido:

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.0906 usec per loop
$ python -m timeit -s "import numpy as np" "np.random.randint(2, size=1)"
100000 loops, best of 3: 4.65 usec per loop

$ python -m timeit -s "from random import random" "test = [random() < 0.5 for i in range(1000000)]"
10 loops, best of 3: 118 msec per loop
$ python -m timeit -s "import numpy as np" "test = np.random.randint(2, size=1000000)"
100 loops, best of 3: 6.31 msec per loop
 0
Author: ojunk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 10:09:58

Una nueva visión de esta cuestión implicaría el uso de Faker que se puede instalar fácilmente con pip.

from faker import Factory

#----------------------------------------------------------------------
def create_values(fake):
    """"""
    print fake.boolean(chance_of_getting_true=50) # True
    print fake.random_int(min=0, max=1) # 1

if __name__ == "__main__":
    fake = Factory.create()
    create_values(fake)
 -2
Author: Althea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 22:16:49