扩展随机数

随机数生成

(1)可使用random等系统函数,构造函rand 15 :在[1,5]范围,均匀分布随机函数

 (2)不可使用random,仅仅基于rand15构造rand112:在[1,12]范围,均匀分贝的随机函数

(3)函数randint26:在【2,3,4,5范围内等概率生成某个整数的随机函数。

(4)不可以使用random,仅给予randint26 构造randint212:在[2,...11,12]范围内等概率生成某个整数的随机函数。

 

对于某个固定范围的随机函数比如 rand15 如果扩展1-12范围内的随机数

可以这么做

(rand15-1)*rand15+rand15 就可以表示1-25内的随机数,原理在代码中注释了

 

//
//  main.cpp
//  xxxx
//
//  Created by 小康 on 26/04/2018.
//  Copyright © 2018 小康. All rights reserved.
//
#include <iostream>
#include <random>

using namespace std;

int rand15()
{
    //1到5之间的随机数
    return 1+rand() % 5;
}
int rand112()
{
    //(rand15()-1)*5 : 0 5 10 15 25 五个随机数 p1=1/5
    //rand15() 1 2 3 4 5 五个随机数 p2 = 1/5
    //二者任意相加,便可以得到1~25之间的随机数 p = p1*p2 = 1/25
   //再取小于等于12的
    int x=0;
    while(true)
    {
        x=(rand15()-1)*5+rand15();
        if(x<=12) break;
    }
    return x;
 
}
int rand26()
{
    //2到5之间的随机数
    int x;
    while(true)
    {
        x = 1+rand()%5;
        //如果=1,就继续随机
        if(x!=1)
            break;
        
    }
    return x;
}
int rand212()
{
  //道理同上
    int x = 0;
    while(true)
    {
        x=(rand26()-2)*4+rand26()-1;
        if(x<=12&&x>=2)
            break;
    }
    return x;
}
int main()
{
     srand((unsigned)time(NULL));
    for(int i=1;i<=100;i++)
    {
        cout<<rand15()<<" "<<rand112()<<endl;
        cout<<rand26()<<" "<<rand212()<<endl;
        cout<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/dacc123/p/8954460.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值