mardi 15 septembre 2015

Generate random numbers with uniform distribution (getting same number in loop)

I need to generate random numbers between two specified numbers in a loop with a uniform distribution. I am using the library offered by c++11. Problem is that i keep getting the same number in the loop. It is required that the number generated on every loop pass be different. Code below:

#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <random>
using namespace std;

double randnum (double a, double b)
{
  std::default_random_engine generator;
  std::uniform_real_distribution<double> distribution (a,b);
  double num=distribution(generator);

  return num;
}


int main()
{
    int np=100;

    double umin =0;
    double umax=0.5;
    double u[np];

    for (int i=0;i<np;i++)
    {
        u[i]=randnum(umin,umax);
        cout<<u[i]<<endl;
    }    
}

Please help. Any advice on generating random number by any other alternate means is welcome, but it must have a uniform distribution.

Thanks




Aucun commentaire:

Enregistrer un commentaire