Random Number Generator

An exercise is to write a program that generates random numbers within user specified limits. The program I wrote is as follows and it runs correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "../../std_lib_facilities.h"

void randnum(double lower, double upper, int n)  // Generate 'n' random numbers uniformly distributed 
{	                                         // between lower and upper limits.
	double a = 0;
	double b = 0;

	srand((unsigned)time(0));

	for (int i = 1; i < n+1; ++i) {
		a = rand();
		b = lower + (a / 32767) * (upper - lower);   // RAND_MAX for MS VC++ Express is 32,767.
		cout << i <<"  " << b <<endl;
	}
}

int main () 
{
    int z = 0;
    double l = 0;
    double u = 0;

    cout <<"Enter the lower and upper limits for, and the number of random numbers \nto be generated, separated by a space.\n";
    cin >> l >> u >> z;

    randnum(l,u,z);

    keep_window_open();
    return 0;
}


It occurred to me that this only generates numbers uniformly over the range. I have used random number generators that use different probability distributions to generate the numbers. There is uniform, normal, Poisson, binomial, etc. I looked for probability distributions in C++, but found more questions than answers, The math.h header doesn't seem to support any probability functions.

If I want to generate numbers that follow the normal distribution, do I first have to write a function that estimates the normal probability density myself?
(I have done that in Javascript so I think I can do it in C++ as well, but just asking.)
Last edited on
Have a look at Boost.Random:
http://www.boost.org/doc/libs/1_44_0/doc/html/boost_random.html

It supports various generation methods and distributions.
Also, call srand() from within main, not from within your function.
Thanks for the suggestions. I took a look at Boost.org. Right now most of their stuff is beyond my understanding. But I am glad I know it exists!

Thank you for the heads-up on srand(). I now see the difference in calling it each time the function is called, as I have it now, and each time the program is run.
Topic archived. No new replies allowed.