Skip to content

Instantly share code, notes, and snippets.

@joshlk
Last active July 11, 2019 10:22
Show Gist options
  • Save joshlk/5b1a2c3a8d4bcf94476cafa33e611795 to your computer and use it in GitHub Desktop.
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
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