# Saving the state of CRT rand()

This topic is 3856 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have created a randomized algorithm A() for a problem I am solving. I also have a deterministic algorithm B() that solves the same problem. I basically want: Code 1: srand(seed) B() int x = rand() Code 2: srand(seed) A() int y = rand() I want x == y, which I believe involves storing the state of rand() before calling A(). I can't seem to find a function in the CRT that does this.

##### Share on other sites
Can't you just call srand again with the same seed? This will always give you the same results.

##### Share on other sites
yeah i geuss my example was bad in this case, suppose there were an unknown N rands after the srand() and before my function.

##### Share on other sites
rand() is suitable only for the most mundane of random number generation tasks. To get real stuff done, check out boost::random.

##### Share on other sites
One simple way to solve this is to look up the code for a prng and just use that code directly in your app. Then you have complete access to the internal state of the prng.
One such common implementation is shown here: http://www.codeguru.com/forum/archive/index.php/t-312357.html
In this case you declare holdrand in your cpp file, and can happily save and restore the value of it at any time to do exactly what you want.
Of course if you want the extra randomness of some more advanced prng's then that's up to you.

1. 1
Rutin
46
2. 2
3. 3
4. 4
5. 5
JoeJ
18

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632998
• Total Posts
3009802
• ### Who's Online (See full list)

There are no registered users currently online

×