Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a number between 1 and 2 java Math.random() [duplicate]

Tags:

java

random

math

I'm working on creating a range of numbers between 1 and 2 using the imported math.random() class.

Here's how I got it working so far, however I can't see how it would work:

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

Anyonould?e know if that actually works to get the range? if not.. then what

EDIT: Looking for either the number 1 or 2.

like image 853
zeck Avatar asked Dec 01 '22 17:12

zeck


1 Answers

If you want the values 1 or 2 with equal probability, then int temp = (Math.random() <= 0.5) ? 1 : 2; is all you need. That gives you a 1 or a 2, each with probability 1/2.

like image 89
pjs Avatar answered Dec 15 '22 13:12

pjs