article

generating "real" random numbers

Email
Submitted on: 1/3/2015 2:20:00 AM
By: r0m4n (from psc cd)  
Level: Beginner
User Rating: By 5 Users
Compatibility: C, C++ (general), Microsoft Visual C++, Borland C++, UNIX C++
Views: 432
 
     This article tells you how to generate real random numbers using rand(), srand(), and time()

 
				






Generating “real” random numbers



Generating “real” random numbers.

The Problem

Well as you may know rand() returns the next pseudo-random number in the series. The default seed for the series is 1. You can change it by calling srand().But calling srand() doesn’t always mean that you will get “real” random numbers.For example the following code looks like it would return random numbers but it does not:

 

#include <stdlib.h> /* header for rand() and srand() */

#include <stdio.h> /* io header */

int main()

{

srand(rand());

for(int i=0;i<=9;i++)

printf(“%i\n”,rand());

return 0;

}

 

The output of this program will be the same each time you run it. Feel free to test this.

 

Solution

As mentioned above srand() can be used to change the seed. But if you set it to a constant the series would still be the same. So we use srand(time(0)). time() returns a time_t object. You can interpret it as an integer and the value will always differ. So, now we would have:

 

#include <stdlib.h> /* header for rand() and srand() */

#include <stdio.h> /* io header */

#include <time.h> /* header needed for time() */

int main()

{

srand(time(0));

for(int i=0;i<=9;i++)

printf(“%i\n”,rand());

return 0;

}

 

Now we have real random numbers.

 

Contact

If you have any questions/comments e-mail me at r0m4n@yahoo.com

I hope you enjoyed this tutorial, and have a nice day.


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.