Jacob Perkins
Jacob Perkins

Reputation: 25

seed random numbers in c

I am currently trying to teach myself c programming. I am stuck on learning random numbers. Many of the websites I visit use the time() function as a method of seeding the random number generator. But many posts and websites I have read say that using the system clock as a method of producing random numbers is flawed. My question is "what exactly should I be using to generate truly random numbers? Should I just manipulate the numbers with arithmetic or is there something else? To be specific, I'm looking for the "best practices" that programmers follow to generate random numbers in the c programming language.

Here is an example of a website I am talking about:

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042005782&id=1043284385

Upvotes: 2

Views: 19207

Answers (2)

Nex Mishra
Nex Mishra

Reputation: 770

In case if you want a random number, use:

randomize () ; 

m = random(your limit); 
printf("%d", m);// dont forget to include stdlib

Upvotes: -2

Wyzard
Wyzard

Reputation: 34563

srand(time(NULL)) is good enough for general basic use. Its shortcomings are:

  • It's not suitable for cryptography, since it's possible for an attacker to predict the pseudo-random sequence. Random numbers used in cryptography need to be really unpredictable.
  • If you run the program several times in quick succession, the RNG will be seeded with the same or similar values (since the current time hasn't changed much), so you're likely to get similar pseudo-random sequences each time.
  • If you generate very many random numbers with rand, you're likely to find that they're not well-distributed statistically. This can be important if you're doing something like Monte Carlo simulations.

There are more sophisticated RNG libraries available for cryptographic and statistical use.

Upvotes: 9

Related Questions