seed random numbers in c - 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

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.

In case if you want a random number, use:
randomize () ;
m = random(your limit);
printf("%d", m);// dont forget to include stdlib

Related

Always the same output with rand() with different ide envirionment too [duplicate]

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
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.
In case if you want a random number, use:
randomize () ;
m = random(your limit);
printf("%d", m);// dont forget to include stdlib

Logic behind the random number generator in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does a random number generator work?
How does C compiler takes decisions whether which number should be generated next in a random number generation function? For example it always generates a new random number between the given range. How is that done?
It generates the next number by keeping some state and modifying the state every time you call the function. Such a function is called a pseudorandom number generator. An old method of creating a PRNG is the linear congruential generator, which is easy enough:
static int rand_state;
int rand(void)
{
rand_state = (rand_state * 1103515245 + 12345) & 0x7fffffff;
return rand_state;
}
As you can see, this method allows you to predict the next number in the series if you know the previous number. There are more sophisticated methods.
Various types of pseudorandom number generators have been designed for specific purposes. There are secure PRNGs which are slow but hard to predict even if you know how they work, and there are big PRNGs like Mersenne Twister which have nice distribution properties and are therefore useful for writing Monte Carlo simulations.
As a rule of thumb, a linear congruential generator is good enough for writing a game (how much damage does the monster deal) but not good enough for writing a simulation. There is a colorful history of researchers who have chosen poor PRNGs for their programs; the results of their simulations are suspect as a result.
It is not a compiler but a C library that has a function to produce pseudorandom (not truly random!) numbers.
Usually linear congruential generators are used for this.
Well, the C compiler doesn't take that decison. The next random number depends on the algorithm. Generating random number is not an easy task. Take a look at
http://www.math.utah.edu/~pa/Random/Random.html
http://computer.howstuffworks.com/question697.htm
http://en.wikipedia.org/wiki/Random_number_generation
It depends on the specific implementation of the pseudo random number generator (PRNG) in question. There are a great many variants in use.
A common example is the family of linear congruential generators (LCGs). These are defined by a recurrence relation:
Xn+1 <- aXn + c (mod m)
So each new sample from the PRNG is determined solely by the previous sample, and the constants a, c and m. Note that the choice of a, c and m is crucial, as discussed here.
LCGs are very simple and efficient. They are often used for the random number generators provided by the standard library. However, they have poor statistical properties and for better randomness, more advanced PRNGs are preferred.
There are many questions regarding this in stackoverflow. Here are few. You can take help from these.
implementation of rand()
Rand function in c
Rand Implementation
This is actually a really big topic. Some of the key things:
Random number generation is done at run-time, rather than compile-time.
The strategy for providing randomness depends (or should depend) greatly on the application. For example, if you simply need a sequence of values that are evenly distributed throughout the given range, solutions such as a linear congruential generator are used. If your application is security/cryptography related, you'll want the stronger property that your values are both randomly distributed and also unpredictable.
A major challenge is acquiring "real" randomness, which you can use to seed your pseudorandom generator (which "stretches" real randomness into an arbitrary amount of usable randomness). A common technique is to use some unpredictable system state (e.g., sample the location of the mouse, or keypress timing) and then use a pseudorandom generator to provide randomness to the system as a whole.

Random number generator that doesn't use rand()/srand() C functions

I'm developing some library in C that can be used by various user applications.
The library should be completely "transparent" - a user application can init it and finalize,
and it's not supposed to see any change in the running application.
The problem is - I'm using C srand()/rand() functions in the library initialization,
which means that the library does affect user's application - if a user generates random numbers, they will be affected by the fact that rand() was already called.
So, can anyone point to some simple non-GPL alternative to rand() random number generator in C?
It doesn't have to be really strong - I'n not doing any crypto with the numbers.
I was thinking to write some small and really simple generator (something like take time and XOR with something and do something with some prime number and bla bla bla), but I was wondering if someone has a pointer to a more decent generator.
It generates the next number by keeping some state and modifying the state every time you call the function. Such a function is called a pseudorandom number generator. An old method of creating a PRNG is the linear congruential generator, which is easy enough:
static int rand_state;
int rand(void)
{
rand_state = (rand_state * 1103515245 + 12345) & 0x7fffffff;
return rand_state;
}
As you can see, this method allows you to predict the next number in the series if you know the previous number. There are more sophisticated methods.
Various types of pseudorandom number generators have been designed for specific purposes. There are secure PRNGs which are slow but hard to predict even if you know how they work, and there are big PRNGs like Mersenne Twister which have nice distribution properties and are therefore useful for writing Monte Carlo simulations.
As a rule of thumb, a linear congruential generator is good enough for writing a game (how much damage does the monster deal) but not good enough for writing a simulation. There is a colorful history of researchers who have chosen poor PRNGs for their programs; the results of their simulations are suspect as a result.
If C++ is also acceptable for you, have a look at Boost.
http://www.boost.org/doc/libs/1_51_0/doc/html/boost_random/reference.html
It does not only offer one generator, but several dozen, and gives an overview of speed, memory requirement and randomness quality.

What is a suitable replacement for rand()?

As far as I know rand() does not generate a uniform random distribution. What function/algorithm will allow me to do so? I have no need for cryptographic randomness, only a uniform random distribution. Lastly, what libraries provide these functions?
Thanks!
rand() does generate a uniform (pseudo-)random distribution.
The actual requirement, from the C standard (3.7 MB PDF), section 7.20.2.1, is:
The rand function computes a sequence of pseudo-random integers in
the range 0 to RAND_MAX.
where RAND_MAX is at least 32767. That's admittedly vague, but the intent is that it gives you a uniform distribution -- and in practice, that's what implementations actually do.
The standard provides a sample implementation, but C implementations aren't required to use it.
In practice, there are certainly better random number generators out there. And one specific requirement for rand() is that it must produce exactly the same sequence of numbers for a given seed (argument to srand()). Your description doesn't indicate that that would be a problem for you.
One problem is that rand() gives you uniformly distributed numbers in a fixed range. If you want numbers in a different range, you have to do some extra work. For example, if RAND_MAX is 32767, then rand() can produce 32768 distinct values; you can't get random numbers in the range 0..9 without discarding some values, since there's no way to evenly distribute those 32768 distinct values into 10 equal sized buckets.
Other PRNGs are likely to give you better results than rand(), but they're still probably going to be subject to the same issues.
As usual, the comp.lang.c FAQ answers this better than I did; see questions 13.15 through 13.21.
Here's an article and a stand-alone random number generator written in C#. The code is very small and easily portable to C++ etc.
Whenever this subject comes up, someone responds that you should not use your own random number generator but should leave that up to specialists. I respond that you should not come up with your own algorithm. Leave that up to specialists because it is indeed very subtle. But it's OK and even beneficial to have your own implementation. That way you know what's being done, and you could use the same method across languages or platforms.
The algorithm in that article is by George Marsaglia, a top expert in random number generation. Even though the code is tiny, the method holds up well to standard tests.
The BSD random() function (included in the XSI option of POSIX/SUS) is almost universally available and much better than rand on most systems (except some where rand actually uses random and thus they're both pretty good).
If you'd rather go outside the system libraries, here's some good information on your choices:
http://guru.multimedia.cx/category/pseudo-random-number-generators/
(From Michael Niedermayer of FFmpeg fame.)
Well, the question of whether or not an actual pseudorandom generator exists is still open. That being said, a quick search reveals that there may be some slightly better alternatives.

What is a pseudo-random integer?

I am reading a C book. In the description of the rand() function, they say:
rand returns a pseudo-random integer in the range 0 to RAND_MAX.  RAND_MAX is implementation dependent but at least 32767.
I don't understand; what is a "pseudo-random integer"?
Thanks.
Informally, a pseudorandom number is a number that isn't truly random, but is "random enough" for most purposes.
Computers are inherently deterministic devices. The processor executes specific commands in a specific order, and programs control how the processor does so. Consequently, it's hard for programs to generate random numbers because no deterministic process can create a random number. Thus what many programs do is use a pseudorandom number generator, which is a function that produces numbers according to some deterministic formula that appear to be random but actually are not. Most programming languages provide some sort of pseudorandom number generator for general programming use, and when true randomness isn't needed they work just fine.
However, they have their limitations. In cryptographic settings, in many cases true randomness is required in order to prevent attackers from guessing the workings of a system and compromising it, for example. In this case, it is possible to get truly random numbers by using specialized hardware that can amplify background noise or use quantum effects. This sort of randomness is extremely hard to generate, though, and so it's not commonly used unless absolute unpredictability is required.
From wiki entry : Pseudorandom number generator
A pseudorandom number generator
(PRNG), also known as a deterministic
random bit generator (DRBG), is an
algorithm for generating a sequence of
numbers that approximates the
properties of random numbers.
In other words, its approximately random (to a known extent), but not truly random in the sense of random noise from a physical source.
It means that the number may seems to be random but the truth is computer can't generate a truly random number, it works out a number based on a logic which tends to be random.
Like observing time difference in keystrokes, and then using it as just an input in calculating a number. Such things combined with several other inputs tend to give random numbers but in reality its just an algorithm which tends to give random numbers. If the same conditions are matched, it will give the same number.
To add some pedantry to the other correct answers that you've already received, there really is no such thing as a "pseudorandom integer" (or for that matter, a random integer). This is the point that John von Neumann was making in his famous quote (which is usually misleading abbreviated to just the first sentence):
"Any one who considers arithmetical
methods of producing random digits is,
of course, in a state of sin. For, as
has been pointed out several times,
there is no such thing as a random
number — there are only methods to
produce random numbers, and a strict
arithmetic procedure of course is not
such a method"
Consider the number 7. Is it a random integer? If it is, is it a pseudorandom integer or a true random integer? What about the number -10? Clearly these questions don't make sense (obligatory link to xkcd 221).
So, as others have pointed out, what the book actually means is that the number is generated by a pseudorandom (i.e. deterministic) number generator as opposed to being obtained from a truly random sequence. There are several different pseudorandom number generator algorithms and the best ones generate output that is statistically indistinguishable from a true random sequence.
It means that it generates a number sequence that exhibits the properties of a random number in terms of distribution, but which is mathematically generated and deterministic in its output for any particular seed value.
You can see this by creating a program that uses such a function to generate a short sequence, and observing that each time you run it it generates the same sequence. This option surprises the unsuspecting, but is also quite a useful property in testing code. When a less predictable sequence is required, one normally initialised the PRNG with a seed value that is itself unpredictable, often derived from the current system time, since it is not normally predictable when a program will be started.
Pseudo random number generators are not normally suitable for security applications such as data encryption, or on-line gambling applications, where their ultimate predictability could be a serious weakness.
In most computers, a random number is considered psuedorandom because it is not completely random.
pseudo=fake
Basically, the current time is used to generate a random number, so it can be predicted what number will be generated initially, and for most applications, this is fine.

Resources