兰特实施
我想了解 rand() 和 srand() 函数是如何实现的,并想调整代码以将其修改为我的要求。在哪里可以找到 rand() 和 srand() 的源代码。
I would like to go through how rand() and srand() functions are implemented and would like to tweak the code to modify it to my requirements. Where can i find the source code of rand() and srand().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
rand
和srand
通常作为简单的 LCG< /a>,您可以轻松编写自己的代码(只需几行代码),而无需查找rand
和srand
的来源。请注意,如果您需要随机数用于“严肃”目的(例如密码学),那么 RNG 比 LCG 更好。顺便说一句,C 标准本身包含
rand
和srand
的示例实现:rand
andsrand
are usually implemented as a simple LCG, you can easily write your own (it's few lines of code) without looking for the sources ofrand
andsrand
. Notice that, if you need random numbers for "serious" purposes (e.g. cryptography), there are much better RNGs than LCG.By the way, the C standard itself includes a sample implementation of
rand
andsrand
:它采用输入参数中的种子,通常如下所示:-
并返回一个符合概率的随机数,从而返回预期的出现次数。
来自 CodeGuru 论坛:-
希望这会有所帮助。
It takes a seed as in input argument, usually like follows:-
and returns a random number that adheres to the probability and hence expected number of occurrences.
from CodeGuru forums:-
Hope this helps.
glibc(由 gcc 使用)是一个简单的公式:
在 232 处环绕,如图所示 这里。您只需将 x 设置为种子,然后继续调用函数来计算该表达式(并更新种子)。
但您应该知道,像这样的线性同余生成器被认为是足够的,但并不理想。
虽然唯一理想的随机数生成器是完全随机的,但 Mersenne Twister 可能更接近。
The glibc one (used by gcc) is the simple formula:
wrapping around at 232, as shown here. You can just set
x
as the seed then keep calling a function to evaluate that expression (and update the seed).But you should be aware the linear congruential generators like this are considered adequate but not ideal.
While the only ideal random number generator would be perfectly random, the Mersenne Twister probably comes closer.