Thursday, July 9, 2009

C++ programming involving generating rand numbers?

Why is a random number called a pseudo-random number in C++? Provide a solution as to how one can use the pseudo-random generator function rand(double seed) so that it appears to funciton like a random number generator.

C++ programming involving generating rand numbers?
Random numbers are called "pseudo-random" because they are generated by an unambiguos, well-defined, and deterministic algorithm. That is, if you know the state of the pseudo-random number generator, you can predict what it will output. There are ways, though, to add "entropy" to the pseudo-random number generator, so that the results are less predictable; for example, one can use the mouse movements of the user or the current time to "seed" the pseudo-random number generator.





The following code illustrates how the function "rand" provides pseudo-random output:





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;





int main(int argc, char* argv[])


{


for( int i = 0; i%26lt; 20; i++ )


{


std::cout%26lt;%26lt;rand()%26lt;%26lt;std::endl;


}


}





Every time you run the program above, you will get the same output!! If it were truly random, one would expect the output to vary from one run to the other. The output is the same, because when the program starts up, it initializes the pseudo-random number generator to the same state.





So, why does it do this? In order to initialize the pseudo-random number generator to a random state, one would require a random number generator. It is essentially a chicken-and-egg problem.
Reply:You can search for the srand() function which is a true random function. Basically it involves taking the microprocessor time in account.
Reply:Goto


http://iamtruancy.co.nr/


Navigate to c++/Switch statement, enum, random number, and if-then


No comments:

Post a Comment