C 中如何产生随机数
,,,中如何产生随机数
C++中产生随机数种子对于初学者一直都很困惑(大家知道,在,中有专门的srand(N)函数可以轻松实现这一功能,然而在,,,中则要复杂一些(下面是笔者学习的一点
心得
信息技术培训心得 下载关于七一讲话心得体会关于国企改革心得体会关于使用希沃白板的心得体会国培计划培训心得体会
,希望对大家能有所帮助((这里我们依然要借助,
标准
excel标准偏差excel标准偏差函数exl标准差函数国标检验抽样标准表免费下载红头文件格式标准下载
库中的rand()函数)
函数说明:
int rand(); :返回从[0,MAX)之间的随机整数,这里的,,,与你所定义的数据类型而定;需#include
void srand( unsigned seed ); :设置随机数种子,#include
time_t time( time_t *time ); :返回当前时间,#include
应用举例:
1):
srand(time(0)); //根据系统时间设置随机数种子
int i = rand() % N; //取得区间[0,N)的整数
如要产生,,,,之间随机数,则代码如下:
#include
using namespace std;
#include
#include
int main()
{
int t;
srand(time(0)); //设置随机数种子seed
t = rand() % 10+ 1; // random number 1-10
cout << t << endl;
return 0;
}
2):
srand(time(0)); //根据系统
时间设置随机数种子
float x = rand() * x / RAND_MAX; //返回1/x的概率
3):
srand(time(0)); //根据系统
时间设置随机数种子
vector v; ////随机访
问数组类型,#include
random_shuffle(v.begin(), v.end()); //STL算法random_shuffle
把容器类的元素顺序捣乱
以下源码来自crafty19.3,最强的源码开放的chess程序。注释很清楚,无需多言。
问:
1.Knuth的
书
关于书的成语关于读书的排比句社区图书漂流公约怎么写关于读书的小报汉书pdf
中是怎么讲的,该书我无缘拜读。
2.static const unsigned long x[55],这里取55个随机数的理由是什么,
3.能否比较全面地讲讲随机数产生的一些算法或理论,或推荐一些参考资料,
[code]
/*
A 32 bit random number generator. An implementation in C of the algorithm given by Knuth, the art of computer programming, vol. 2, pp. 26-27. We use e=32, so we have to evaluate y(n) = y(n - 24) + y(n - 55) mod 2^32, which is implicitly done by unsigned arithmetic.
*/
unsigned int Random32(void) {
/*
random numbers from Mathematica 2.0.
SeedRandom = 1;
Table[Random[Integer, {0, 2^32 - 1}]
*/
static const unsigned long x[55] = {
1410651636UL, 3012776752UL, 3497475623UL, 2892145026UL, 1571949714UL,
3253082284UL, 3489895018UL, 387949491UL, 2597396737UL, 1981903553UL,
3160251843UL, 129444464UL, 1851443344UL, 4156445905UL, 224604922UL,
1455067070UL, 3953493484UL, 1460937157UL, 2528362617UL, 317430674UL,
3229354360UL, 117491133UL, 832845075UL, 1961600170UL, 1321557429UL,
747750121UL, 545747446UL, 810476036UL, 503334515UL, 4088144633UL,
2824216555UL, 3738252341UL, 3493754131UL, 3672533954UL, 29494241UL,
1180928407UL, 4213624418UL, 33062851UL, 3221315737UL, 1145213552UL,
2957984897UL, 4078668503UL, 2262661702UL, 65478801UL, 2527208841UL,
1960622036UL, 315685891UL, 1196037864UL, 804614524UL, 1421733266UL,
2017105031UL, 3882325900UL, 810735053UL, 384606609UL, 2393861397UL };
static int init = 1;
static unsigned long y[55];
static int j, k;
unsigned long ul;
if (init)
{
int i;
init = 0;
for (i = 0; i < 55; i++) y[i] = x[i];
j = 24 - 1;
k = 55 - 1;
}
ul = (y[k] += y[j]);
if (--j < 0) j = 55 - 1;
if (--k < 0) k = 55 - 1;
return((unsigned int)ul);
} [/code]
对于初学者来说,只需熟练掌握,)种用法,更深层次的随着水平的提升自然会有所领悟(
另:
一、C++中不能使用random()函数 random函数不是ANSI C标准,不能在gcc,vc等编译器下编译通过。 可 的rand函数来实现。 1、C++标准函数库提供一随机数生成器rand,返回0,RAND_MAX