C++中三种产生随机数的方法

第一种方法:使用时间做为生成随机数的种子

#include <iostream>

using namespace std;

// randomly generate 0 or 1
int main()
{
  srand((unsigned)time(0));
  for(int i = 0; i < 10; i++)
  {
    cout << rand() % 2 << "";
  }
  cout << endl << endl;
  return 0;
}

第二种方法:使用C++提供的生成随机数的库函数

#include <iostream>
#include <random>

using namespace std;

// randomly generate 0 or 1
int main()
{
  default_random_engine e(time(0));
  uniform_int_distribution<unsigned>u(0,1);
  for(int i = 0; i < 10; i++)
  {
    cout << u(e) << "";
  }
  cout << endl << endl;
  return 0;
}

第三种方法参考Simple Random Number Generation

private static uint GetUint()
{
    m_z = 36969 * (m_z & 65535) + (m_z >> 16);
    m_w = 18000 * (m_w & 65535) + (m_w >> 16);
    return (m_z << 16) + m_w;
}

public static double GetUniform()
{
    // 0 <= u < 2^32
    uint u = GetUint();
    // The magic number below is 1/(2^32 + 2).
    // The result is strictly between 0 and 1.
    return (u + 1.0) * 2.328306435454494e-10;
}

m_z、m_w仅被初始化一次,GetUint函数返回无符号整数的随机数序列,GetUniform返回在(0,1)之间的随机浮点数,这个方法相比于以上两种方法的好处是上述两种方法,在不同的时刻产生的随机数序列不同,结果不可复现,而第三种方法产生的随机数序列始终相同,任意时刻运行程序的结果相同

注意事项:使用上述三种方法生成随机数序列时,种子只初始化一次,若重复初始化操作,则可能导致多次生成的随机数序列相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值