Take the 2-minute tour ×

I need to randomly pick a number (this is in java, using Math.random()) between -N and N. Specifically, in this current case I need to pick a random number between -1 and 1. All the results I've found has explained how to find a random number between some positive numbers.

Right now I'm using this statement, which only covers half of what I need.

double i = Math.random();
share|improve this question
Yucky, yucky, but just for fun: double i = Math.random() * (Math.random() > 5 ? -1 : 1);. (although this offers 2x the amount of numbers compared to the typical solution) –  Ryan Amos Sep 24 '12 at 3:45
add comment

5 Answers

up vote 3 down vote accepted

For a random number between -n and n:

 * @return a random number, r, in the range -n <= r < n
public static double getRandom(double n) {
   return Math.random()*n*2 - n;
share|improve this answer
Picking nits, but the range is actually -n <= r < n. –  Joachim Isaksson Sep 24 '12 at 3:33
True, but equality holds with a probability of somewhere around 1 in 4 billion –  Thorn Sep 24 '12 at 3:35
add comment

Just use:

2 * Math.random() - 1
share|improve this answer
add comment

The general formula for generating random numbers uniformly distributed within a range (min, max) is:

min + rand.nextDouble() * (max - min)

In your case, max == -min == N. Just plug in the values and simplify:

2 * N * rand.nextDouble() - N
share|improve this answer
add comment

use random on

(0, 32767+32768) then subtract by 32768

or Generate numbers between 0 and 65535 then just subtract 32768

share|improve this answer
add comment

Try this:

double n = 1.0;
double range = 2 * n;
double value = range * Math.random() - n;

You can modify the n value to alter the maximum/minimum value generated, for example if you need random numbers in the range [-10, 10) then let n = 10.0;

share|improve this answer
Limit is actually 2x the maximum number. Perhaps it would be apt to name it range? –  Ryan Amos Sep 24 '12 at 3:44
@RyanAmos agreed, I updated my answer –  Óscar López Sep 24 '12 at 4:05
add comment

Your Answer


