_random.pxd 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Authors: Arnaud Joly
  2. #
  3. # License: BSD 3 clause
  4. cimport numpy as cnp
  5. ctypedef cnp.npy_uint32 UINT32_t
  6. cdef inline UINT32_t DEFAULT_SEED = 1
  7. cdef enum:
  8. # Max value for our rand_r replacement (near the bottom).
  9. # We don't use RAND_MAX because it's different across platforms and
  10. # particularly tiny on Windows/MSVC.
  11. # It corresponds to the maximum representable value for
  12. # 32-bit signed integers (i.e. 2^31 - 1).
  13. RAND_R_MAX = 2147483647
  14. cpdef sample_without_replacement(cnp.int_t n_population,
  15. cnp.int_t n_samples,
  16. method=*,
  17. random_state=*)
  18. # rand_r replacement using a 32bit XorShift generator
  19. # See http://www.jstatsoft.org/v08/i14/paper for details
  20. cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil:
  21. """Generate a pseudo-random np.uint32 from a np.uint32 seed"""
  22. # seed shouldn't ever be 0.
  23. if (seed[0] == 0):
  24. seed[0] = DEFAULT_SEED
  25. seed[0] ^= <UINT32_t>(seed[0] << 13)
  26. seed[0] ^= <UINT32_t>(seed[0] >> 17)
  27. seed[0] ^= <UINT32_t>(seed[0] << 5)
  28. # Use the modulo to make sure that we don't return a values greater than the
  29. # maximum representable value for signed 32bit integers (i.e. 2^31 - 1).
  30. # Note that the parenthesis are needed to avoid overflow: here
  31. # RAND_R_MAX is cast to UINT32_t before 1 is added.
  32. return seed[0] % ((<UINT32_t>RAND_R_MAX) + 1)