随机化算法之随机数

首先是介绍:

代码如下:

//随机数类
//Random.hpp
//=====================================================
#ifndef RANDOM_HPP
#define RANDOM_HPP

#include<ctime>

const unsigned long maxshort = 65536L;
const unsigned long multiplier = 1194211693L;
const unsigned long adder = 12345L;

class RandomNumber{
private:
    //当前种子
    unsigned long randSeed;
public:
    RandomNumber(){};
    RandomNumber(unsigned long s = 0);  //构造函数,默认值0表示由系统自动产生种子
    unsigned short Random(unsigned long n);  //产生0:n-1之间的随机整数
    double fRandom(void);  //产生[0 , 1)之间的随机整数
};

RandomNumber::RandomNumber(unsigned long s)  //产生种子
{
    if (s == 0)
    {
        randSeed = time(0);  //使用系统时间产生随机种子
    }
    else
    {
        randSeed = s;
    }
}

unsigned short RandomNumber::Random(unsigned long n)  //产生 0:n-1之间的随机整数
{
    randSeed = multiplier * randSeed + adder;
    return(unsigned short)((randSeed >> 16) % n);
}

double RandomNumber::fRandom(void)  //产生[0 , 1)之间的随机数
{
    return Random(maxshort) / double(maxshort);
}

#endif
//随机数
//main.cpp
//==============================================
#include <iostream>
#include <iomanip>
#include "Random.hpp"

using namespace std;

int TossCoins(int numberCoins)
{
    //随机抛硬币
    static RandomNumber coinToss(0);
    int tosses = 0;
    for (int i = 0; i < numberCoins; i++)
    {
        tosses += coinToss.Random(2);
    }
    return tosses;
}

int main(void)
{
    //模拟随机抛硬币事件
    const int NCOINS = 10;
    const long NTOSSES = 50000L;
    //heads[i]是得到i次正面的次数
    long heads[NCOINS + 1];
    int position;
    //初始化数组heads
    for (int i = 0; i < NCOINS + 1; i++)
    {
        heads[i] = 0;
    }
    //重复50000次试验
    for (int j = 0; j < NTOSSES; j++)
    {
        heads[TossCoins(NCOINS)] ++;
    }
    //输出频率图
    for (int i = 0; i < NCOINS; i++)
    {
        position = int(float(heads[i]) / NTOSSES * 72);
        cout << setw(6) << i << " ";
        for (int j = 0; j < position - 1; j++)
        {
            cout << " ";
        }
        cout << "*" << endl;
    }

    system("pause");
}

 结果如下(频率图):

猜你喜欢

转载自www.cnblogs.com/zf-blog/p/9064433.html
今日推荐