如何获得浮动范围之间的随机数?

问题:如何获得浮动范围之间的随机数?

randrange(start, stop)只接受整数参数。那么,如何在两个浮点值之间获得一个随机数呢?

randrange(start, stop) only takes integer arguments. So how would I get a random number between two float values?


回答 0

使用random.uniform(a,b)

>>> random.uniform(1.5, 1.9)
1.8733202628557872

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

回答 1

random.uniform(a, b)似乎是您要寻找的。从文档:

返回一个随机浮点数N,使得a <= N <= b表示a <= b,b <= N <= a表示b <a。

这里

random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.


回答 2

如果您想生成一个随机浮点数,该浮点数的右边是N个数字,则可以执行以下操作:

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

第二个参数是小数位数。

if you want generate a random float with N digits to the right of point, you can make this :

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

the second argument is the number of decimals.


回答 3

最常见的是,您将使用:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

如果需要,Python可提供其他发行版

如果已经numpy导入,则可以使用其等效项:

import numpy as np
np.random.uniform(a, b) # range [a, b)

同样,如果需要其他发行版,请numpy提供与python相同的发行版,以及许多其他发行版

Most commonly, you’d use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.