Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Float Random Values (also negative)

Tags:

c

random

How can i generate float random values in C? (also negative)

like image 759
Zany Avatar asked Oct 18 '25 18:10

Zany


1 Answers

In general to generate random numbers from an arbitrary distribution you'd first generate uniform random numbers and then pass them to the inverse of the cumulative distribution function.

Assume for example that you want random numbers with uniform distribution on the interval [-10.0, 10.0] and all you've got is random numbers from [0.0, 1.0]. Cumulative distribution function of the uniform distribution on [-10.0, 10.0] is:

cdf(x) = 0.05 * x + 0.5   for x in [-10.0, 10.0]

This expresses the probability that a random number generated is smaller than x. The inverse is

icdf(y) = 20.0 * y - 10.0   for y in [0.0, 1.0]

(You can obtain this easily on paper by switching the x and y axis).

Hence to obtain random numbers uniformly distributed on [-10.0, 10.0] you can use the following code:

#include <stdlib.h>

// Returns uniformly distributed random numbers from [0.0, 1.0].
double uniform0to1Random() {
    double r = random();
    return r / ((double)RAND_MAX + 1);
}

// Returns uniformly distributed random numbers from [-10.0, 10.0].
double myRandom() {
  return 20.0 * uniform0to1Random() - 10.0;
}

In fact, you don't need uniform0to1Random() since there are already a lot of good uniform random numbers generators from [0.0, 1.0] (e.g. in the boost library).

You can use the method to generate random numbers with nearly any probability distribution you want by sampling the inverse cumulative distribution as shown above.

See http://en.wikipedia.org/wiki/Inverse_transform_sampling for more details.

like image 87
Adam Zalcman Avatar answered Oct 20 '25 09:10

Adam Zalcman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!