【发布时间】:2023-04-07 16:42:01
【问题描述】:
出于一致性原因,我正在尝试让 numpy 使用我自己的 RNG 实现。我的理解是,根据我能从 numpy 文档here 和here 中找到的少量文档,我需要提供一个自定义 BitGenerator 类来实现random_raw 方法,然后使用np.random.Generator 进行初始化,所以我试过这个:
import numpy as np
class TestBitGenerator(np.random.BitGenerator):
def __init__(self):
super().__init__(0)
self.counter = 0
def random_raw(self, size=None):
self.counter += 1
if size is None:
return self.counter
return np.full(n, self.counter)
mc_adapter = TestBitGenerator()
npgen = np.random.Generator(mc_adapter)
print(npgen.random())
导致段错误:
$ python bitgen.py
Segmentation fault (core dumped)
我假设我在这里遗漏了一些东西(来自 TestBitGenerator?),谁能指出我正确的方向?
我尝试不对 np.random.BitGenerator 进行子类化,但得到了不同的错误:
object has no attribute 'capsule'
我使用 numpy 1.19.2 和 python 3.8.2
【问题讨论】:
-
如果是出于一致性的原因,为什么不直接将种子设置为一致的值呢?
-
解释我的确切需求似乎与问题无关,因为它很复杂。我有一些 C++ 代码(包括我的 RNG)通过 pybind11 传输到 python,并且我在 MPI 上运行,我需要控制每个进程的播种方式,并且每个进程应该(理想情况下)只使用一个可从两者访问的随机流C++ 和 python 层。
标签: python-3.x numpy random