Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Math.random() from -N to N

Tags:

java

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();
like image 938
yiwei Avatar asked Jul 03 '26 11:07

yiwei


2 Answers

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;
}
like image 69
Thorn Avatar answered Jul 06 '26 02:07

Thorn


Just use:

2 * Math.random() - 1
like image 22
Keith Randall Avatar answered Jul 06 '26 00:07

Keith Randall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!