随机数生成入门总结

rand()

在很多时候我们都会用到随机数,比如代码测试,想自己制造一些数据,许多人也会第一时间想到rand()这个随机生成的函数

来自官方的解释:

不喜欢看英文的小伙伴可以跳过

function
<cstdlib>
int rand (void);
Generate random number

Returns a pseudo-random integral number in the range between 0 and RAND_MAX.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

RAND_MAX is a constant defined in <cstdlib>.

A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

1
2
3
v1 = rand() % 100;         // v1 in the range 0 to 99
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;   // v3 in the range 1985-2014 
 



Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).

C++ supports a wide range of powerful tools to generate random and pseudo-random numbers (see <random> for more info).

传送门

 言归正传,rand()是通过某种算法,产生一个随机序列然后从中选出,并生成一个伪随机数,如果只是用rand的话,你会发现无论你的程序运行多少次,你得到的随机数都是一样的

然后我们继续想,如果不赋值,直接输出rand,结果会一样吗?

 

 结果并不是我们想象的那样,一直不变,原因就是rand生成的是伪随机数,也就是它是通过某种方式生成了一段数的序列,也就是说我们打印的相当于是已经打乱顺序,储存好在数组的元素,因为随机种子一直没变。

由于种子没变,随机序列也就没变,也就是说你用某种算法产生了一个伪随机数列,提前存储在一个数据结构里面,然后每次rand的时候就把序列中的元素拿出来一个。(可以想象成一个数组,每次调用rand,指针向后移一位)

(个人观点,欢迎斧正)

想要多次生成不同的的随机数就需要用到下面的这个函数。

srand

srand也包含在cstdlib里面,此函数是为了生成随机种子,然后让系统产生的随机数不同,通常我们可以结合time使用,time能获取系统时间,让种子不断的随着时间变化,这样就能产生不同的随机数列,也就能用rand产生不同的随机数

time的头文件为ctime

具体食用方法如下:

 现在产生的随机数每次运行都不一样。

code:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<ctime>
//头文件觉得写着麻烦的话可以偷偷懒,写一个#include<bits/stdc++.h>就行
using namespace std;
int main(void)
{
    srand((int)time(0));//这里也可以用NULL代替time里面的0
    cout<<rand()<<endl;
    return 0;
}

以上就是我对随机数的入门看法,进阶的话等我有时间在更叭

补充:

今天在书上又看到了随机数,我觉得自己写一个随机数和随机种子的函数(其实也很简单)。

先说下原理:我们通过某种计算公式(可DIY),实现对随机数生成的模拟,设置一个全局变量表示种子,

然后各一个种子的值,我们就可以用time的返回值作为种子,然后根据我们自定义的公式进行伪随机数的生成。

代码如下:

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define maxn 105 
#define PI acos(-1)
int key=1;//种子初始化
int myrand(void)
{
    key=key*1234567+119699;//自定义伪随机数生成公式
    return (key/1234) %32768;
}
void mysrand(int seed)
{
    key=seed;//种子变化
}
int main(void)
{
    mysrand((int)time(0));
    printf("%d
",myrand());
}

随机数进阶:mt19937

原文地址:https://www.cnblogs.com/Mangata/p/13372222.html