Generating Random Numbers in C++

Hi,

Generating random numbers have always been a headache for scientists, since no computer generated numbers are truly random. There are some natural phenomenon considered truly random, like the time elapsed  between two counts in a Gieger counter or Brownian motion. I saw a beautiful piece of code from stackexchage the other day and I thought of sharing it with everyone. It is called “Minimal” random number generator of Park and Miller. It generates random numbers from 0 to 1 and is fairly efficient for Monte Carlo sampling codes. I’m attaching the code along with the source.

Have a nice day!

Arjun

using namespace std;
#include<iostream>

#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define MASK 123459876

long idum=-1;
float ran0(long *idum)
{
long k;
float ans;
*idum ^= MASK;
k=(*idum)/IQ;
*idum=IA*(*idum-k*IQ)-IR*k;
if (*idum < 0) *idum += IM;
ans=AM*(*idum);
*idum ^= MASK;
return ans;
}

main()
{
for (int j=1;j<=5;j++)
{
cout <<ran0(&idum)<<endl;
}
}

Source:Cross OS distributed computing

As mentioned by our dear friend, a time seed can be added to make it even better. Here is a modified version.

using namespace std;
#include<iostream>
#include<iomanip>
#include<fstream>
#include<ctime>
#include<cstdlib>
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define MASK 123459876

long idum=-1;
float ran0(long *idum)
{
long k;
float ans;
*idum ^= MASK;
k=(*idum)/IQ;
*idum=IA*(*idum-k*IQ)-IR*k;
if (*idum < 0) *idum += IM;
ans=AM*(*idum);
*idum ^= MASK;
return ans;
}

main()
{
srand(time(0));

ofstream ofile("RandomNumbers.txt");
for(int i=1;i<4;i++)
{
idum=rand();
for (int j=1;j<=10;j++)
{
cout << ran0(&idum)    << endl;
ofile << ran0(&idum)<<endl;
}

ofile <<00000000000<< endl;
}
ofile.close();
}

One thought on “Generating Random Numbers in C++

Leave a comment