Generating very good random numbers

Hello everyone

Please forgive the state of this code, I have quite literally only started coding C++ today. My question is related to rand() and generating very good random numbers (whatever that actually means).

I would be grateful if somebody could look at this code and tell me if it will yield a "better" random number than simply seeding with the current time.

Thank you for any and all help.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(){
	
	// Initially seed rand() with the current time
	srand((unsigned)time(0)); 
	
	// General Variables 
	int random;
	char restart;
	int select_seed;
	int seed;
	int random_integer[20];
	unsigned int random_list[2000];

do {

	// Generate 2000 random numbers and load into an array
	for (int counter = 0; counter <= 2000; counter++){
		random = rand();
		random_list[counter] = random;}

	//Randomly select one element from the array
	select_seed = ((rand()%2000)+1);
	seed = random_list[select_seed];
		
	//Seed rand() with the result
	srand(seed);
		
	//Generate & display 20 random numbers using the seed created by the above procedure
		for (int counter = 0; counter < 20; counter++) {
			random_integer[counter] = ((rand()%1000)+1);
			cout << random_integer[counter] << endl;}

	cout << "\n\nMore... (Y)";
	cin >> restart;
	
        } while (restart == 'Y' || restart == 'y');
	
	return 0;
}
Last edited on
rand is not really good in generating 'very good random numbers', you should look for some external library.
And I dont like much the goto you have on line 41, it can be easily replaced by a do-while
Yes, I agree! I have just done a quick google and found out that goto is outlawed by the civilized c++ community. ;) Thank you.
Hello Ishtar,

I have found an article about the rand() function with suggestions how to use it when I first tried to use it myself.
http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx

Nevertheless, as Bazzy already pointed out, you might find better random number generators.

Have a nice day



Last edited on
Topic archived. No new replies allowed.