在线咨询
eetop公众号 创芯大讲堂 创芯人才网
切换到宽版

EETOP 创芯网论坛 (原名:电子顶级开发网)

手机号码,快捷登录

手机号码,快捷登录

找回密码

  登录   注册  

快捷导航
搜帖子
查看: 2046|回复: 0

[转贴] glibc 里面rand函数的实现

[复制链接]
发表于 2020-3-24 13:34:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册

x




  1. #include <stdlib.h>


  2. /* This algorithm is mentioned in the ISO C standard, here extended
  3.    for 32 bits.  */
  4. int
  5. rand_r (unsigned int *seed)
  6. {
  7.   unsigned int next = *seed;
  8.   int result;

  9.   next *= 1103515245;
  10.   next += 12345;
  11.   result = (unsigned int) (next / 65536) % 2048;

  12.   next *= 1103515245;
  13.   next += 12345;
  14.   result <<= 10;
  15.   result ^= (unsigned int) (next / 65536) % 1024;

  16.   next *= 1103515245;
  17.   next += 12345;
  18.   result <<= 10;
  19.   result ^= (unsigned int) (next / 65536) % 1024;

  20.   *seed = next;

  21.   return result;
  22. }


复制代码


As you can see, it's simply multiply with an addition and a shift. The values are carefully chosen to make sure that you get no repeat of the output for RAND_MAX iterations.
Note that this is an old implementation which has been replaced by a more complex algorithm: [color=var(--blue-700)]https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=stdlib/random_r.c;hb=HEAD
If the link if broken, Google for "glibc rand_r"

https://stackoverflow.com/questions/1026327/what-common-algorithms-are-used-for-cs-rand

您需要登录后才可以回帖 登录 | 注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条


小黑屋| 手机版| 关于我们| 联系我们| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2025-7-17 12:40 , Processed in 0.012623 second(s), 8 queries , Gzip On, MemCached On.

eetop公众号 创芯大讲堂 创芯人才网
快速回复 返回顶部 返回列表