Last active
July 11, 2019 10:22
-
-
Save joshlk/5b1a2c3a8d4bcf94476cafa33e611795 to your computer and use it in GitHub Desktop.
Random numbers in Cython. Random integers and floating points from the standard library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from libc.stdlib cimport rand, srand, RAND_MAX | |
from libc.time cimport time | |
def get_RAND_MAX(): | |
return RAND_MAX | |
""" | |
unsigned long is at least 32 bits and so in the range [−2,147,483,647, +2,147,483,647] | |
""" | |
## Need to seed random numbers with time otherwise will always get same results | |
srand(time(NULL)) | |
cdef inline long randint(long lower, long upper) nogil: | |
"""Has the limitation that rand() only produces random integers upto RAND_MAX | |
which is guaranteed to be at least 32767 and usually 2,147,483,647 but this can vary on different systems. | |
Also the quality of random number aren't guaranteed and vary between systems""" | |
return rand() % (upper - lower + 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment