【问题标题】:32-bit floats from NumPy random generator来自 NumPy 随机生成器的 32 位浮点数
【发布时间】:2022-01-21 11:54:21
【问题描述】:

在过去几年中,NumPy 中的随机数生成进行了彻底改革。设置可重现随机数的现代方式现在是这样的:

# Set up random number generator
import numpy as np
stream = np.random.PCG64DXSM
seed = 42
rng = np.random.Generator(stream(seed))

# Draw random numbers from various distributions
a = rng.uniform (0, 1, size=10)  # uniform  distribution
b = rng.normal  (0, 1, size=10)  # normal   distribution
c = rng.rayleigh(1,    size=10)  # Rayleigh distribution
...

这项工作很棒。三个数组abc 都包含双精度浮点数,即它们的dtypenp.float64。我将如何将其更改为例如np.float32?

我当然可以将结果转换为 32 位,但这不是最佳的(如果我们将问题扩展到 128 位,这根本不起作用)。 docs 支持获取 32 位结果,但我不知道如何使用上述首先使用 np.random.Generator(stream(seed)) 定义 rng 的系统。另一个doc entry 表示

接受 np.float32 或 np.float64 的可选 dtype 参数 ...

但我似乎又找不到在上面的哪个地方可以放置这样的论点。

以前曾询问过similar question,但所有结果都属于旧的 NumPy 接口,而不是上面展示的现代接口。

具体来说,让我们关注最新版本的 NumPy (1.22),它确实带有一些 changes 来生成随机数,尽管我认为只是修复了一些错误。

【问题讨论】:

  • 你试过 np.random.Generator(stream(seed),dtype=np.float32)
  • @David 是的,numpy.random._generator.Generator.__init__() 不允许使用 dtype 关键字。

标签: python python-3.x numpy random floating-point


【解决方案1】:

您链接到的文档是指“接受 np.float32 或 np.float64 以生成用于选择分布的单精度或双精度均匀随机变量的可选 dtype 参数”;事实上,只有四个“选择分布”接受dtype 参数:random([0, 1) 上的均匀分布)、standard_exponentialstandard_gammastandard_normal

例如,

In [26]: rng = np.random.default_rng()

In [27]: rng.random(size=10, dtype=np.float32)
Out[27]: 
array([0.13855255, 0.33742118, 0.51912105, 0.59625137, 0.9547056 ,
       0.20756459, 0.4408238 , 0.37817073, 0.62999   , 0.36310232],
      dtype=float32)

In [28]: rng.standard_gamma(shape=6.5, size=10, dtype=np.float32)
Out[28]: 
array([ 4.99139  ,  7.1637936,  5.1287727,  5.8192725,  7.1051316,
        1.9996499, 14.339245 ,  6.158779 ,  5.6176057,  6.186189 ],
      dtype=float32)

对于其他发行版,您必须按照您的建议生成 64 位值并转换为 float32

【讨论】:

  • @EricPostpischil,关于从 float64 转换为 float32 的要点。幸运的是,random 方法是具有 dtype 参数的分布之一,因此您不必将 float64 输出转换为 float32。如果要float32,使用dtype=np.float32直接获取float32输出。
  • 对不起,我不知道是什么让我认为这里有转换。 (我希望例程不会在内部进行转换,但我对此没有信心;通过生成一个 32 位整数并除以 2^32 来返回“浮点”结果对某人来说非常容易,这将舍入一些值到 1。也许有人可以生成几亿个 float32 值,看看它们中是否有一个正好是 1?)
  • @EricPostpischil numpy 正在做 (next_uint32(bitgen_state) >> 8) * (1.0f / 16777216.0f) 这对我来说看起来很合理
猜你喜欢
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
相关资源
最近更新 更多