Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers from -n to n in C

Tags:

c

random

I want to generate random numbers from -n to n excluding 0. Can someone provide me the code in C? How to exclude 0?

like image 899
avd Avatar asked Nov 04 '09 09:11

avd


2 Answers

One idea might be to generate a random number x in the range [1,2n], inclusive. Then return -(x - n) for x larger than n, else just return x.

This should work:

int my_random(int n)
{
  const int x = 1 + rand() / (RAND_MAX / (2 * n) + 1);

  return x > n ? -(x - n) : x;
}

See the comp.lang.c FAQ for more information about how to use rand() safely; it explains the above usage.

like image 73
unwind Avatar answered Nov 15 '22 04:11

unwind


The simplest thing I can suggest to do is to generate a Random number between 0 and 2n and then to do the math trick:

result= n - randomNumber 

Although 0 might be very unlikely you can check for that using an If and redo the random number generation.

like image 27
Chris Avatar answered Nov 15 '22 03:11

Chris