Question

Hello i am trying to simulate some job scheduling algorithms and i am trying to create a poisson arrival function for the requests. I found the algorithm for poisson arrival on wikipedia and i impleneted it and runned it but i get the same results all the time (ex l=15 -> returns 14 , l=1/15 returns 0)

#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
main (){
for (int i=0;i<1000;i++)
{

float l=25;
float L=exp(-l);
float k=0;
float p=1;
//begin while
do{ 
k=k+1;
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
double u = rand() / (double)RAND_MAX;   
p=p*u;
}   while (p>L);    
return k-1;
}}

This is the algorithm that i used to create this

algorithm poisson random number (Knuth):
init:
     Let L ← e−λ, k ← 0 and p ← 1.
do:
     k ← k + 1.
     Generate uniform random number u in [0,1] and let p ← p × u.
while p > L.
return k − 1.

thanks in advance

Was it helpful?

Solution

Your question is slightly unclear but I think your problem is that you are expecting different random numbers each time you run your program. Note that rand() will generate the same sequence of random numbers every time you run your program unless you provide it with some sort of seed value.

The standard way to do this is to use the current time to seed the random number generator, as below.

#include <iostream>
#include <ctime>
#include <cstdlib>

int main() {
    srand(time(NULL));
    std::cout << rand();

    return 0;
}

This will produce a different random sequence each time. If you were to remove the srand(time(NULL)) line, you would get the same result every time you ran the program.

You only need to call srand(time(NULL)) once at the start of your program.

EDIT: I'm just also going to edit my post to mention that there is a dedicated 'random' header in C++11, I haven't used this yet so I can't comment much on it, but you can read about it here

http://www.cplusplus.com/reference/random/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top