1

I am trying to generate random arrivals via poisson distribution for my project. The code part:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <random>
#include <ctime>
int nextTime(double lambda,int timeslots,int PU_number);

int main()
{
    srand(time(0));
    //some code
    nextTime(4,time_slots,PU_number);
}
int nextTime(double lambda,int timeslots,int PU_number)
{
    int mat[PU_number][timeslots];
    std::default_random_engine generator;
    std::poisson_distribution<int> distribution(lambda);
    int number;
    int total=0;
    for(int i=0; i< PU_number;i++)
    {
        total=0;
        for(int j=0;j<timeslots;j++)
        {
            number = distribution(generator);
            total+=number;
            mat[i][j]=total;//another matrix, not relevant here
            cout<<number<<" ";
        }
        cout<<endl;
    }
    return 0;
}

Above code always produces same numbers. what is wrong here?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
WhoCares
  • 225
  • 1
  • 5
  • 16

1 Answers1

2

srand seeds rand, not your std::default_random_engine. To seed this, use

std::default_random_engine generator(std::random_device{}());
                                     ^^^^^^^^^^^^^^^^^^^^^^
                                     e.g., any seed can go here
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • I changed it with yours. but now, it stops when compiler tries to execute your line in debug mode. – WhoCares Jan 31 '15 at 13:19
  • aha. I changed `std::random_device{}()` to `time(0)` and it works correctly. Thanks dude. – WhoCares Jan 31 '15 at 13:21
  • The code is [fine](http://coliru.stacked-crooked.com/a/4ea388acb07857ad), seems to be a bug in your compiler. (Is it MinGw under Windows?) Just use another seed instead. – Baum mit Augen Jan 31 '15 at 13:22