0

Is this the correct way to generate a random number from (-1, 36)?:

  #include <stdio.h>
  #include <stdlib.h>
  #define RAND_MAX 36

  int main()
  {           
      int num = (-1) + (36 + 1) * (rand()/(RAND_MAX+1));
      printf("%d\n", num);
      return 0;
  }
Nikita
  • 23
  • 1
  • 1
  • 4

3 Answers3

8

Do you know how to get random number in the range zero to N (where N is whatever max number you want in the range)? Then you know how to generate number in the range -N to N as well.

Simply generate a number in the range 0 to 2*N and subtract N.


Update: To generate a number in the range -1 to 36, then you should generate from 0 to 37 and subtract 1.

The principle is the same in both cases though.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

No, it is not the correct way.

First you should not #define RAND_MAX 36 as RAND_MAX is already a define telling the maximum value rand() will generate on your system.

A very simple solution is this:

To get numbers in the range [0:37] you can do

rand() % 38;  // % is the reminder when dividing by 38 - aka modulo

then just `subtract 1

However - see this link for a better distribution

Why do people say there is modulo bias when using a random number generator?

Community
  • 1
  • 1
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

That depends on whether you are trying to generate integers or floats from -1 to 36.

~

For integers:

1) First, generate a range from 0 to N. From -1 to 36 (inclusive), you have 38 integers.

rand()%38; //this generates a range of integers from 0 to 37.

2) Shift the range:

rand%38 - 1; //this shifts the range of numbers to -1 to 36.

~

For floats (or numbers with decimal points):

1) generate a "continous" range from 0 to 1.

( 1.0*rand() )/RAND_MAX; //do not forget to convert rand() to a float so that you will not get 0 from integer division.

2) Scale the range:

37 * ( (1.0*rand() )/RAND_MAX; //this scales the range to (0, 37)

3) Shift the range:

37 * ( (1.0*rand() )/RAND_MAX - 1; //this shifts to range (-1, 36)
Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17
  • Since op prints with `%d`, integer results must be expected. Your integer solution is just repeating my answer. – Support Ukraine Apr 12 '16 at 17:04
  • @4386427 He also did write `rand()/RAND_MAX` somewhere in his code. Thus it is not fully clear whether he is expecting an `integer` or `float` range. – Lincoln Cheng Apr 12 '16 at 17:06
  • @4386427 That might have been a mistake. It is equally likely that he is expecting a continuous range given that he wrote `rand()/RAND_MAX` also. That is why I provided both an `integer` and `float` solution. – Lincoln Cheng Apr 12 '16 at 17:11
  • @4386427 Dont worry, if he is expecting an `integer` range, I will remove my solution. I'm just putting it here for now so that the questioner can take a look at the solution for a continuous range. – Lincoln Cheng Apr 12 '16 at 17:13