我正在进行一项m/m/2/2的离散事件模拟。结果与理论值相同,这意味着程序是正确的(在Ubuntu的g++环境下)。然而,在Windows中(Visual Studio),只有当试验次数少于10000时才能得到正确的结果。我调试了很长时间,最终发现必须使用
(double) rand() / ( RAND_MAX + 1 )
而不是(double) rand() / RAND_MAX
。为什么会这样?这两个编译器生成的随机数是不同的吗?#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <cmath>
#include "iomanip"
#include <queue>
using namespace std;
#define TRIAL_NUM 10000000
//structure that represent a customer
struct cust
{
int cust_id;
double arrival_time;
double depart_time;
};
//uniform random generator
double uniRand()
{
return (double) rand() / RAND_MAX;
}
//exponential random generator
double expRand(double lam)
{
double u,x;
u=uniRand();
x=(-1/lam)*log(1-u);
return(x);
}
int main()
{
//seed the random generator
srand (time(NULL));
//queue that hold all customers
std::queue<cust*> customers;
double lam = 0, mu = 0;
bool showStatus = false;
cout<<"M/M/1/1 Discrete Event Simulation with "<<TRIAL_NUM<<" customers\n"<<" Please spacify the value of lambda:";
cin>>lam;
while(lam<= 0)
{
cout<<"lambda value must be a positive number, try again:";
cin>>lam;
}
cout<<"Please specify the value of mu:";
cin>>mu;
while(mu<= 0)
{
cout<<"lambda value must be a positive number, try again:";
cin>>mu;
}
cout<<"Show status for each customer? (y/n)";
char show;
cin>>show;
while( tolower(show) != 'y' && tolower(show) != 'n')
{
cout<<"Invalid input, try again:";
cin>>show;
}
if ( tolower(show) =='y' )
{
showStatus = true;
}
//Generating all arrival time, service time for all customers
double temp_time = 1;
cust* temp;
for (int i = 1; i <= TRIAL_NUM; ++i)
{
temp= new cust;
temp -> arrival_time = temp_time + expRand(lam);
temp_time = temp->arrival_time;
temp->depart_time = temp->arrival_time + expRand(mu);
temp->cust_id = i;
customers.push(temp);
}
//Blocking customer count
double block = 0;
bool blockFlag = false;
temp = customers.front();
double server1 = 0, server2 = 0;
//perform simulation
while( !customers.empty())
{
if ( server1 < temp->arrival_time)
{
server1 = temp->depart_time;
}
else if ( server2 < temp->arrival_time)
{
server2 = temp->depart_time;
}
else
{
block++;
blockFlag = true;
}
if (showStatus)
{
cout<<"Customer "<<temp->cust_id<<"\tarrived at:"<<temp->arrival_time<<"\tservice time:"<<temp->depart_time<<"\tstatus:";
if (blockFlag)
{
cout<<"Blocked"<<endl;
}
else{
cout<<"Served"<<endl;
}
}
customers.pop();
if (!customers.empty())
{
temp = customers.front();
}
blockFlag = false;
}
cout<<"Blocking probability is: "<<block/TRIAL_NUM<<endl;
return 0;
}