使用numpy生成高斯随机数原来是我在蒙特卡洛模拟中的瓶颈,在此我大量使用PyOpenCl。
np.random.randn(int(1e9))
因此,我也在寻找一种用PyopenCl生成高斯分布随机数的方法。
我发现一个6岁的线程在问类似的问题。但是我不确定如何在PyOpenCl中使用VexCL库:Gaussian distributed random numbers in OpenCL
任何想法如何实现与PyOpenCl中的np.random.randn类似的良好RNG?
似乎pyopencl已经包含一个随机数生成器:
https://github.com/inducer/pyopencl/blob/master/pyopencl/clrandom.py
运行简单的测试表明,平均值和标准偏差与numpy的实现相当。有谁知道进一步的测试来检查随机数生成器的质量?
import pytest
from pyopencl.clrandom import RanluxGenerator
import pyopencl as cl
import numpy as np
def test_compare_to_numpy_rand():
context = cl.create_some_context()
queue = cl.CommandQueue(context)
rng = RanluxGenerator(queue=queue)
mu = 1.0
sigma = 6
size = (int(1e7))
numbers = rng.normal(shape=size, mu=mu, sigma=sigma, dtype=np.float, cq=queue)
mu_meas = np.mean(numbers.get())
sigma_meas = np.std(numbers.get())
numbers_np = mu + sigma* np.random.randn(size)
assert pytest.approx(mu_meas, 1e-2) == mu
assert pytest.approx(sigma_meas, 1e-2) == sigma
assert pytest.approx(mu_meas, 1e-2) == numbers_np.mean()
assert pytest.approx(sigma_meas, 1e-2) == numbers_np.std()