Cómo obtener un número aleatorio entre un rango flotante?


randrange(start, stop) solo toma argumentos enteros. Entonces, ¿cómo obtengo un número aleatorio entre dos valores flotantes?

Author: martineau, 2011-05-22

3 answers

Use aleatorio.uniforme (a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872
 446
Author: Yuri Stuken,
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-05-22 13:04:33

random.uniform(a, b) parece ser lo que buscas. De los documentos:

Devuelve un número de coma flotante aleatorio N tal que a

Ver aquí.

 57
Author: garnertb,
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-05-22 13:53:03

Si desea generar un flotador aleatorio con N dígitos a la derecha del punto, puede hacer esto:

round(random.uniform(1,2), N)

El segundo argumento es el número de decimales.

 7
Author: Baurin Leza,
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-28 12:21:56