yiwei
yiwei

Reputation: 4190

java Math.random() from -N to N

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();

Upvotes: 3

Views: 1339

Answers (5)

Óscar López
Óscar López

Reputation: 236140

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;

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

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

Upvotes: 1

Thorn
Thorn

Reputation: 4057

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;
}

Upvotes: 3

Ravindra Bagale
Ravindra Bagale

Reputation: 17673

use random on

(0, 32767+32768) then subtract by 32768

or Generate numbers between 0 and 65535 then just subtract 32768

Upvotes: 0

Keith Randall
Keith Randall

Reputation: 23265

Just use:

2 * Math.random() - 1

Upvotes: 1

Related Questions