Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand changes value without changing seed

Take the following program:

#include <cstdlib>
using std::rand;

#include <iostream>
using std::cout;

int main()
{
    cout << rand() << ' ' << rand() << ' ' << rand() << '\n';
}

Due to rand producing the same values as long as the seed isn't changed using srand, this should produce three identical numbers.
e.g.

567 567 567

However, when I run this program it gives me three different values.
e.g.

6334 18467 41

When the program is (compiled and) run again, the same three numbers are generated. Shouldn't I have to use srand to change the seed before I start getting different results from rand? Is this just my compiler/implementation trying to do me a favour?

OS: Windows XP
Compiler: GCC 4.6.2
Libraries: MinGW

EDIT: By trying to use srand, I discovered that this is the result from a seed of 1 (which I guess is made default).

like image 830
chris Avatar asked Apr 05 '12 16:04

chris


2 Answers

Each call to rand() will always generate a different random number.

The seed actually determines the sequence of random numbers that's created. Using a different seed will get you another 3 random numbers, but you will always get those 3 numbers for a given seed.

If you want to have the same number multiple times just call rand() once and save it in a variable.

like image 196
ThomasG Avatar answered Oct 29 '22 16:10

ThomasG


Calling rand() multiple times intentionally produces a different random number each time you call it.

Unless your program calls srand() with a different value for each run, the sequence will be the same for each run.

You could use srand() with the time to make the entire sequence different each time. You can also call srand() with a known value to reset the sequence - useful for testing.

See the documentation for rand() and srand().

like image 34
RichieHindle Avatar answered Oct 29 '22 15:10

RichieHindle