Does Python have a function to mimic the sequence of C's rand()?

两盒软妹~` 提交于 2021-02-04 08:24:09

问题


I am looking for a Python function that will mimic the behavior of rand() (and srand()) in c with the following requirements:

  1. I can provide the same epoch time into the Python equivalent of srand() to seed the function
  2. 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 than RAND_MAX, and RAND_MAX can differ between C implementations.


来源:https://stackoverflow.com/questions/60331996/does-python-have-a-function-to-mimic-the-sequence-of-cs-rand

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!