# Creating Random Numbers

The problem with creating random numbers is that you need to start with something random. If you call rand() without doing anything special, you will ALWAYS get the same sequence of numbers each time you run the program. Not very random.

What we need to do is to seed the random number generator with a random number. Since the exact time that a program is run is relatively random, we can use the time to seed the random generator. The time(NULL) function returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC. Thus everytime we run our program it is is different. The srand() function takes a random number, and "seeds" the rand() function. If we call srand(time()) at hte start of the program a different seed each run will produce a different random number sequence.

Also - you often need to get a random double that is between 0 and 1. rand() returns an int between 0 and RANDOM_MAX. The follwoing code produces a series of numbers between 0 and 1:

### Example that correctly produces random double between 0 and 1

#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream>
using namespace std;

int main ()
{
srand(time(NULL));  // Call only once!

for (int i = 0 ; i< 5 ; i++) {
double random = ((double)rand())/RAND_MAX;
cout << random << " ";
}

return 0;
}
Run 1:
0.717048 0.344757 0.670546 0.326622 0.215806
Run 2:
0.210569 0.936961 0.0785603 0.824302 0.418012
Run 3
0.304646 0.297736 0.999341 0.356471 0.0105336

### Example with seed: (ideone link)

#include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include using namespace std;

int main () { srand(time(NULL)); for (int i = 0 ; i< 10 ; i++) { cout << rand() << " "; } cout << rand();

return 0; } %ENDCODE%

###### Output:
Run 1:
2133349703 1224137931 955459329 692667387 481015798 2117874616 1139140376 102154339 932138766 1287420039 2018517191
Run 2:
1039480801 1457540383 1772964191 1247379874 1473224093 2017816113 1078266250 2110191290 1706701601 11306160 1876620368
Run 3
952434325 217315538 1403067194 192440223 1345012404 399031793 1717634657 1644472273 205876469 1191006621 1420132853

### Example with no seed: (ideone link)

#include <stdlib.h>     /* rand */
#include <iostream>
using namespace std;

int main ()
{
for (int i = 0 ; i< 10 ; i++) {
cout << rand() << " ";
}
cout << rand();

return 0;
}
###### Output:
Run 1:
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421 1025202362
Run 2:
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421 1025202362
Run 3
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421 1025202362
Topic revision: r2 - 2015-10-07 - JimSkon

Copyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback