Aluode/PerceptionLabPortable
0
1# Authors: The scikit-learn developers
2# SPDX-License-Identifier: BSD-3-Clause
3
4from ._typedefs cimport uint32_t
5
6
7cdef inline uint32_t DEFAULT_SEED = 1
8
9cdef enum:
10 # Max value for our rand_r replacement (near the bottom).
11 # We don't use RAND_MAX because it's different across platforms and
12 # particularly tiny on Windows/MSVC.
13 # It corresponds to the maximum representable value for
14 # 32-bit signed integers (i.e. 2^31 - 1).
15 RAND_R_MAX = 2147483647
16
17
18# rand_r replacement using a 32bit XorShift generator
19# See http://www.jstatsoft.org/v08/i14/paper for details
20cdef 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
26 seed[0] ^= <uint32_t>(seed[0] << 13)
27 seed[0] ^= <uint32_t>(seed[0] >> 17)
28 seed[0] ^= <uint32_t>(seed[0] << 5)
29
30 # Use the modulo to make sure that we don't return a values greater than the
31 # maximum representable value for signed 32bit integers (i.e. 2^31 - 1).
32 # Note that the parenthesis are needed to avoid overflow: here
33 # RAND_R_MAX is cast to uint32_t before 1 is added.
34 return seed[0] % ((<uint32_t>RAND_R_MAX) + 1)
35 