内部random()函数 - 如何实现? [英] Inside random() function - How is it implemented?

查看:748
本文介绍了内部random()函数 - 如何实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通常使用random()函数在C ++中创建随机数。

We commonly use random() function to create random numbers in C++.

使用void srand(unsigned int seed)会改善结果,因为它会根据seed的值生成随机数。

The use of void srand (unsigned int seed) would improve the results since it would generate random numbers depending on the value of seed.

任何人都可以告诉我如何实现随机函数?

Can anyone tell me how the random function is actually implemented?

推荐答案

这里是对GNU C库的random()函数中使用的算法的详细描述。

Here is a detailed description of the algorithm used in the GNU C library's random() function.

基本上:

#include <stdio.h>

#define MAX 1000
#define seed 1

main() {
  int r[MAX];
  int i;

  r[0] = seed;
  for (i=1; i<31; i++) {
    r[i] = (16807LL * r[i-1]) % 2147483647;
    if (r[i] < 0) {
      r[i] += 2147483647;
    }
  }
  for (i=31; i<34; i++) {
    r[i] = r[i-31];
  }
  for (i=34; i<344; i++) {
    r[i] = r[i-31] + r[i-3];
  }
  for (i=344; i<MAX; i++) {
    r[i] = r[i-31] + r[i-3];
    printf("%d\n", ((unsigned int)r[i]) >> 1);
  }
}

这篇关于内部random()函数 - 如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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