[SciPy-Dev] Generate random variates using Cython
Andrew Nelson
andyfaff at gmail.com
Wed Jan 22 21:58:31 EST 2020
Christoph, this might give you a headstart.
%%cython
import numpy as np
cimport numpy as np
cimport cython
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
from numpy.random cimport bitgen_t
from numpy.random import PCG64
@cython.boundscheck(False)
@cython.wraparound(False)
def rvs(rand_state, Py_ssize_t n):
"""
Create an array of `n` uniformly distributed doubles.
A 'real' distribution would want to process the values into
some non-uniform distribution
"""
cdef Py_ssize_t i
cdef bitgen_t *rng
cdef const char *capsule_name = "BitGenerator"
cdef double[::1] random_values
if isinstance(rand_state, np.random.RandomState):
randoms = rand_state.uniform(size=n)
elif isinstance(rand_state, np.random.Generator):
x = rand_state.bit_generator
capsule = x.capsule
# Optional check that the capsule if from a BitGenerator
if not PyCapsule_IsValid(capsule, capsule_name):
raise ValueError("Invalid pointer to anon_func_state")
# Cast the pointer
rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
random_values = np.empty(n, dtype='float64')
with x.lock, nogil:
for i in range(n):
# Call the function
random_values[i] = rng.next_double(rng.state)
randoms = np.asarray(random_values)
else:
raise RuntimeError("rand_state wasn't a RandomState or Generator")
return randoms
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/scipy-dev/attachments/20200123/10867155/attachment.html>
More information about the SciPy-Dev
mailing list