generating random number with a specific distribution in c - c

i need a library with functions for generating random number, given average, standard deviation and using one of three distribution - exponential, normal or unified.
even one of the three would help.
i'm looking for something like this - http://www.codeproject.com/KB/recipes/zigurat.aspx, but in c.
thanks

May I recommend the GNU Scientific Library either for use or for inspiration? It has several Random Number Distributions and is designed to be used from C and C++.

uniform:
Generate a random number in the range [0,1] with uniform distribution:
double X=((double)rand()/(double)RAND_MAX);
Exponentional
generating an exponentional random variable with parameter lambda:
-ln(U)/lambda (where U~Uniform[0,1]).
normal:
the simplest way [though time consuming] is using the central limit theorem, [sum enough uniformly distributed numbers] but there are other methods in the wikipedia page such as the box muller transform that generates 2 independent random variables: X,Y~N(0,1)
X=sqrt(-2ln(U))*cos(2*pi*V)
Y=sqrt(-2ln(U))*sin(2*pi*V)
where U,V~UNIFORM[0,1]
transforming from X~N(0,1) to Z~N(m,s^2) is simple: Z = s*X + m
Though you CAN generate these random numbers, I stand by #Amigable Clark Kant suggestion to use an existing library.

Related

How do I generate normally distributed positive integers in C?

I am writing a program in C that requires generating a normal distribution of positive integers with mean less than 1.
You can normalize data that is already normally distributed, for example take data for average length of human beings (180 centimeter) and scale every number by a factor so that the mean becomes less than 1 e.g. multiply every length by 1/180.
I used a Poisson random number generator function in C, which takes the mean as input. I used a combination of rand() followed by exponentiation to get the distribution, which is the normal way to do this, as in Calculation of Poisson distribution in C.
Since I generate 2^14 random numbers, by Central Limit theorem, their distribution will tend to a normal distribution, with the same mean and variance.

generate uncorrelated number in the C language using rand()

I want to generate uncorrelated random number to do a simulation... However, the numbers generated by the rand() function in the C language are correlated. Is there any possibility to use the rand() function and generate multiple random streams? I mean, if the rand() function generate for me a series of correlated numbers, can I cut this series into different streams. Then use these streams independently?
Thanks
You are indeed correct. They are normally autocorrelated as the normal generator implementation is linear congruential (although the C standard does not mandate this). As such an x-y plot of successive numbers will fail a chi square test for random 2D dispersion.
Depending on your application, you could look at Bays-Durham shuffle which, to my knowledge, passes the diehard test for randomness: it's aim is to defeat autocorrelation effects.
I direct you to www.nr.com for an implementation and the rand1, rand2 functions in particular. A more modern way is to use a mersenne twister scheme but a little tricker to implement (by the way C++11 has this generator as part of its standard library).
If your C implementation has rand_r, you can try that. It lets you specify a location to store the state.
Or just use your own pseudo-random number generator.
You may use arc4random or better ar4random_uniform to increase randomness of generated values (actually ar4random_uniform proves you uniformly distributed values).
Generating true random numbers on a computer is impossible, you can only generate "pseudo-random" numbers i.e. numbers that "looks like" random.
Usually one will use a ''seed'' (small sequence of bits) with enough entropy and then "expand" it thanks to a Pseudo-Random-Number-Generator.
C rand() function generates poor quality of randomness, try PRNG that have been proposed in other answers/comments. Some examples:
Mersenne Twister (widely used)
ANSI X9 (adopted by FIPS standard)

Converting a Uniform distribution to Poisson distribution

I have to write a C program to convert a uniform distribution of random numbers (say from 0 to 1) to a poisson distribution. Can anyone help?
Use GSL, the Gnu Scientific Library. There's a function called gsl_ran_poisson:
This function returns a random integer from the Poisson distribution with mean mu.
The probability distribution for Poisson variates is,
p(k) = {\mu^k \over k!} \exp(-\mu)
for k >= 0.
Otherwise, look at the code and copy the ideas.
I am assuming you want to write a C program that can sample a random number from the Poisson Distribution, given a random number in U(0,1).
Generally, this is done by taking the inverse CDF of the number from U(0,1). For discrete distributions like Poisson, one first transforms it to a continuous distribution by assuming that the CDF function is smooth between the integer points, and then we apply appropriate approximations (floor function).
The book Numerical Recipes in C++ (3rd Ed) has the complete explanation and C++ code as well. sec 7.3.12, page 372.

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.

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.

Resources