Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Random double in interval [-1000, 1000]

Tags:

java

random

In java I have:

Random random = new Random();
double randomNum = random.nextDouble();

which creates a random number between 0 and 1. However I want a number between -1000 and 1000, how would I scale this?

Thanks


1 Answers

2 possibilities:

  1. [less dense]: multiple your results by 2000, and subtract 1000 from the result. It won't be as 'dense' as possibility 2.
  2. get a random int in range [-1000,999], and add a random double in range [0,1].

Note that possibility 2 ensures better randomness and better 'density' of your numbers, at the cost of 2 random calls [which might be expansive, if it is an issue].

like image 122
amit Avatar answered Nov 19 '25 21:11

amit