C/C++生成随机数

随机数的用途

  • 单元测试
  • 游戏抽奖
  • 仿真及安全
  • and so on

c++产生随机数

生成器(engine):能够产生离散的等可能分布数值

- 如线性同余法(linear_congruential_engine)
- 梅森旋转法(meraenne_twister_engine)
- 滞后Fibonacci(substract_with_carry_engine)

分布器(distribution):能够把generator均匀分布值映射到其他常见分布

- 如均匀分布(unifor)
    - uniform_int_distribution 整数均匀分布
    - uniform_real_distribution 浮点数均匀分布
- 正态分布(normal) (仅有yes/no两种结果,概率一个p,一个1-p)
- 二项分布(binorial)
- 泊松分布(poisson)
#include <random>

default_random_engine e{}; // default engine
// distribution将产生的随机数映射到整数1..6
uniform_int_distribution<int> one_to_six{1, 6};
// 产生一个符合指定规则的随机数
#include <random>

int x = u(e); 

auto dice{bind(u, e)};
int y = dice();
#include <random>

// 产生随机数
int rand_int(int low, int high)
{
    using namespace std;
    static default_random_engine e;
    using Dist = uniform_int_distribution<int>;
    static Dist u{};
    return u(e, Dist::param_type{low, high});
}

C语言实现随机数

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*
// Maximum value that can be returned by the rand function:
#define RAND_MAX 0x7fff

_ACRTIMP void __cdecl srand(_In_ unsigned int _Seed);

_Check_return_ _ACRTIMP int __cdecl rand(void);
*/
void show() {
  printf("rand()------------
");
  for (int i = 0; i < 10; ++i)
    printf("%d |", rand());
  printf("
");
}
void show_range(int a, int b) { // 固定范围的随机数
  for (int i = 0; i < 10; ++i)
    printf("%d |", rand() % (b - a) + a);
  printf("
");
}
void func() {
  printf("-------test start------------
");
  show(); /*rand() == rand(1)*/
  printf("-------srand(1)--------------
");
  srand(1);
  show();
  printf("-------srand(11111)----------
");
  srand(11111);
  show();
  printf("-------srand(time(NULl))-----
");
  srand(time(NULL));
  show();
  printf("-------test end--------------
");
  return;
}
-------test start------------
rand()------------
41 |18467 |6334 |26500 |19169 |15724 |11478 |29358 |26962 |24464 |
-------srand(1)--------------
rand()------------
41 |18467 |6334 |26500 |19169 |15724 |11478 |29358 |26962 |24464 |
-------srand(11111)----------
rand()------------
3554 |26670 |1503 |15804 |24395 |27484 |20568 |13190 |2698 |7943 |
-------srand(time(NULl))-----
rand()------------
16547 |21195 |9007 |7453 |12018 |30665 |27311 |4207 |12232 |15391 |
-------test end--------------

  1. rand函数产生随机数(收获果实)

    int rand();

    头文件为<stdlib.h>

  2. srand设置随机数种子(播种种子)

    void srand( unsigned seed );

  3. 不设置种子值时,默认种子为1,即srand(1)

  4. 为保证每个 程序每次产生的随机数不同,使用前可以参考使用时间作为种子

    srand(time(NULL))

    添加头文件<time.h>

  5. rand不是线程安全的函数(原则是每个线程的种子不一致)

    1. posix的替代方案时rand_r(int *seed)
    2. 可以使用线程id作为种子来处理

本文来自博客园,作者:flxx,转载请注明原文链接:https://www.cnblogs.com/faithlocus/p/15506903.html

原文地址:https://www.cnblogs.com/faithlocus/p/15506903.html