马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
- #include <stdlib.h>
- /* This algorithm is mentioned in the ISO C standard, here extended
- for 32 bits. */
- int
- rand_r (unsigned int *seed)
- {
- unsigned int next = *seed;
- int result;
- next *= 1103515245;
- next += 12345;
- result = (unsigned int) (next / 65536) % 2048;
- next *= 1103515245;
- next += 12345;
- result <<= 10;
- result ^= (unsigned int) (next / 65536) % 1024;
- next *= 1103515245;
- next += 12345;
- result <<= 10;
- result ^= (unsigned int) (next / 65536) % 1024;
- *seed = next;
- return result;
- }
复制代码
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. If the link if broken, Google for "glibc rand_r"
https://stackoverflow.com/questions/1026327/what-common-algorithms-are-used-for-cs-rand
|