【问题标题】:Using NumPy to generate a sequence of random integers with variable max/min使用 NumPy 生成具有变量 max/min 的随机整数序列
【发布时间】:2018-03-16 12:54:49
【问题描述】:

numpy.random.uniform 支持数组参数,但 numpy.random.randint 不支持:

import numpy as np 
two_random_uniforms = np.random.uniform([0, 1], [3, 4])
this_raises_exception = np.random.randint([0, 1], [3, 4])

我想要的第二行代码的行为相当于:

result = []
for lown, highn in zip([0, 1], [3, 4]):
    result.append(np.random.randint(lown, highn))

有没有办法在不编写 Python 循环的情况下使用变量 max/min 完成随机整数生成?对于我的应用程序所需的大型阵列,上述解决方法的速度会慢得令人无法接受。我可以在 Cython 中编写循环,但如果可能的话,我宁愿使用 NumPy。

【问题讨论】:

    标签: python performance numpy random


    【解决方案1】:

    您可以做的一件简单的事情就是生成浮点数并将它们四舍五入。

    def my_randint(low, high):
        return np.floor(np.random.uniform(low, high))
    

    这个过程可能会稍微调整生成的分布,以使某些整数稍微比其他整数更有可能,但除非您正在使用密码学或其他一些敏感的应用程序,否则它可能会获胜没关系。

    【讨论】:

      猜你喜欢
      • 2015-06-05
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2020-05-10
      • 2014-01-06
      相关资源
      最近更新 更多