问题
I am looking for a Python function that will mimic the behavior of rand() (and srand()) in c with the following requirements:
- I can provide the same epoch time into the Python equivalent of srand() to seed the function
- The equivalent of rand()%256 should result in the same char value as in c if both were provided the same seed.
So far, I have considered both the random library and numpy's random library. Instead of providing a random number from 0 to 32767 as C does though both yield a floating point number from 0 to 1 on their random functions. When attempting random.randint(0,32767), I yielded different results than when in my C function.
TL;DR Is there an existing function/libary in Python that follows the same random sequence as C?
回答1:
You can use random.seed(). The following example should print the same sequence every time it runs:
import random
random.seed(42)
for _ in range(10):
print(random.randint(0, 32768))
Update: Just saw the last comment by the OP. No, this code won't give you the same sequence as the C code, because of reasons given in other comments. Two different C implementations won't agree either.
回答2:
You can't make a Python version of rand
and srand
functions "follo[w] the same random sequence" of C's rand
and srand
because the C standard doesn't specify exactly what that sequence is, even if the seed is given. Notably:
rand
uses an unspecified random number algorithm, and that algorithm can differ between C implementations, including versions of the same standard library.rand
returns values no greater thanRAND_MAX
, andRAND_MAX
can differ between C implementations.
来源:https://stackoverflow.com/questions/60331996/does-python-have-a-function-to-mimic-the-sequence-of-cs-rand