3

I am creating a random number from 1-100, I was looking at some Stackoverflow questions to look for the proper way and I got confused by the many different suggestions. What is the difference between using this:

    int random= (int)(Math.random()*((100-1)+1));

this:

int random= (int)(Math.random()*(100);

and this:

    int random= 1+ (int)(Math.random()*((100-1)+1));
Michel Tamer
  • 341
  • 1
  • 3
  • 10
  • Well, the first two are equivalent (besides the mismatched parenthesis) and return an integer between 0 and 99 inclusive, and the second returns an integer between 1 and 100, inclusive. – Vortico Apr 06 '14 at 01:26
  • possible duplicate of [Generating random numbers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java) – guido Apr 06 '14 at 01:27
  • 1
    it's not a duplicate, he's asking for which one is the correct and / or the logic of each – Frakcool Apr 06 '14 at 01:30
  • This question amounts to "What's the difference between `((100-1)+1)` and `100`?" and "What difference does adding 1 to an expression make?". I wish there were more thought put into some Stack Overflow questions. – Dawood ibn Kareem Apr 06 '14 at 01:50

3 Answers3

5
int random = (int)(Math.random()*(x);

This sets random equal to any integer between 0 and x - 1.

int random = 1 + (int)(Math.random()*(x);

Adding 1 to the overall expression simply changes it to any integer between 1 and x.

(int)(Math.random()*((100-1)+1))

is redundant and equivalent to

(int)(Math.random()*(100)

So take note that:

1 + (int)(Math.random()*(x) returns an int anywhere from 1 to x + 1

but

(int)(Math.random()*(x + 1) returns an int anywhere from 0 to x + 1.

Mdev
  • 2,440
  • 2
  • 17
  • 25
3

I recommend that you use Random and nextInt(100) like so,

java.util.Random random = new java.util.Random();
// 1 to 100, the 100 is excluded so this is the correct range.
int i = 1 + random.nextInt(100);

it has the added benefit of being able to swap in a more secure random generator (e.g. SecureRandom). Also, note that you can save your "random" reference to avoid expensive (and possibly insecure) re-initialization.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

The first is equivalent to the second. Both will give a random integer between 0 and 99 (inclusive, because Math.random() returns a double in the range [0, 1)). Note that (100-1)+1 is equivalent to 100.

The third, will give an integer between 1 and 100 because you are adding 1 to the result above, i.e. 1 plus a value in the range [0, 100), which results in the range [1, 101).

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73