【问题标题】:How to get a random number between a float range?如何获得浮点范围之间的随机数?
【发布时间】:2011-08-30 14:13:21
【问题描述】:

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

【问题讨论】:

  • 如果你想要 numpy,它是 np.random.uniform(start, stop)np.random.uniform(start, stop, samples) 如果你想要多个样本。否则下面的答案是最好的。

标签: python random floating-point


【解决方案1】:

根据我处理 python 的经验,我只能说 random 函数可以帮助生成随机浮点数。以下面的例子为例;

import random

# Random float number between range 15.5 to 80.5
print(random.uniform(15.5, 80.5))

# between 10 and 100
print(random.uniform(10, 100))
The random.uniform() function returns a random floating-point number between a given range in Python

两组代码生成随机浮点数。您可以尝试使用它来满足您的需求。

【讨论】:

    【解决方案2】:

    最常见的是,您会使用:

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

    如果需要,Python 会提供other distributions

    如果你已经导入了numpy,你可以使用它的等价物:

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

    同样,如果您需要另一个发行版,numpy 提供与 python 相同的发行版,以及 many additional ones

    【讨论】:

      【解决方案3】:

      如果你想生成一个随机浮点数,点右侧有 N 个数字,你可以这样:

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

      第二个参数是小数位数。

      【讨论】:

      • 我不知道为什么这个没有更多的赞成票,其他的没有四舍五入机制。
      【解决方案4】:

      random.uniform(a, b) 似乎是您正在寻找的东西。来自文档:

      返回一个随机浮点数 N,使得 a

      here

      【讨论】:

        【解决方案5】:

        使用random.uniform(a, b):

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

        【讨论】:

        • 理论上这会产生 1.5 和 1.9 吗?还是只会产生 1.50~1 和 1.89~?
        • @Musixauce3000 简短回答:是的。更长的答案:如果您查看文档,它指出Returns a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a 换句话说,输出N 可以等于输入ab。在这种情况下,1.51.9
        • 是否有另一种方法可以不使用.uniform 函数,而是使用.randomrandrange
        • @DerryckDX 1.5 + random.random() * (1.9 - 1.5) 应该这样做,即使根据规范,这永远不会完全返回 1.9(即使在理论上)。
        • @Musixauce3000 似乎uniform(a, b) 被实现为a + (b-a) * random() 并返回一个在[a, b) 或[a, b] 范围内的随机数,具体取决于四舍五入 github.com/python/cpython/blob/…
        猜你喜欢
        • 2014-03-31
        • 2021-09-17
        • 2016-09-25
        • 1970-01-01
        • 2010-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多