Re: problem with rand()

From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 12/29/04


Date: Wed, 29 Dec 2004 01:54:14 GMT


<ChasW> wrote...
> given the following example:
>
> Using gcc, this compiles, runs, and outputs as expected, but on
> vc++.net 2003, the first number is always the same despite the time
> seed.
>
> #include <ctime>
> #include <iostream>
>
> using namespace std;
>
> // output 10 numbers ranging from [0, n)
> int main ()
> {
> srand((unsigned int)time(NULL));
>
> int n = 100;
>
> for (int i = 0; i < 10; ++i)
> {
> cout << int(double(rand()) * n / (RAND_MAX + 1.0)) << "\n";
> }
> cout << endl;
>
> return 0;
> }
>
> What am i doing wrong?

First, let me say that it is quite possible that on some hardware RAND_MAX
cannot be represented precisely as a double making it impossible to add 1.0
to it with any effect. But that's really not the problem.

You're scaling your numbers and throwing away the lower part, which _does_
differ from run to run even on VC++. Just print out 'rand()' instead.

It seems that the implementation of the pseudo-random number generator in
the C library shipped with VC++ is rather poor. Try finding a better one
on the Web, it shouldn't be that hard.

Victor



Relevant Pages