Python 有模拟 C 的 rand() 序列的函数吗? [英] Does Python have a function to mimic the sequence of C's rand()?

查看:33
本文介绍了Python 有模拟 C 的 rand() 序列的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 Python 函数,它可以在 c 中模拟 rand()(和 srand())的行为,并满足以下要求:

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

  1. 我可以在与 srand() 等价的 Python 中提供相同的纪元时间来为函数提供种子
  2. 等价的 rand()%256 应该产生与 c 中相同的 char 值,如果两者都提供相同的种子.

到目前为止,我已经考虑了随机库和 numpy 的随机库.而不是像 C 那样提供从 0 到 32767 的随机数,尽管两者都在其随机函数上产生从 0 到 1 的浮点数.在尝试 random.randint(0,32767) 时,我产生了与在 C 函数中不同的结果.

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;博士Python 中是否存在遵循与 C 相同的随机序列的现有函数/库?

TL;DR Is there an existing function/libary in Python that follows the same random sequence as C?

推荐答案

您可以使用 random.seed().以下示例每次运行时都应打印相同的序列:

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))

更新:刚刚看到 OP 的最后一条评论.不,由于其他注释中给出的原因,此代码不会为您提供与 C 代码相同的序列.两种不同的 C 实现也不会一致.

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.

这篇关于Python 有模拟 C 的 rand() 序列的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆