Connecting Tech Pros Worldwide Forums | Help | Site Map

help with generating random numbers between -1 and 1

ILtech's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 6
#1: Oct 3 '08
Math.random() returns a number in the interval [0, 1), right?

So, if I need to change the interval to (-1, 1), would I use do this...

xCoord = Math.random() * 2 - 1;

to change the range to be 2 (so it'd be [0, 2) then subtract one to shift it to (-1, 1)?

Expert
 
Join Date: Sep 2007
Posts: 856
#2: Oct 3 '08

re: help with generating random numbers between -1 and 1


This oughtta work, give it a shot.
Newbie
 
Join Date: Jul 2007
Posts: 9
#3: Oct 4 '08

re: help with generating random numbers between -1 and 1


Don't forget that Math.random() returns a double between 0.0 and 1.0. in order to get the correct results you may need a conditional test.

Maybe something like (yes tertiary, my professor would kill me :) )

Expand|Select|Wrap|Line Numbers
  1. int number = Math.random() >= 0.5 ? 1 : -1;
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: Oct 4 '08

re: help with generating random numbers between -1 and 1


Quote:

Originally Posted by ILtech

Math.random() returns a number in the interval [0, 1), right?

So, if I need to change the interval to (-1, 1), would I use do this...

xCoord = Math.random() * 2 - 1;

to change the range to be 2 (so it'd be [0, 2) then subtract one to shift it to (-1, 1)?

A small nitpick: if you multiply the range [0,1) by two you get the range [0,2);
after subtracting one you get the range [-1,1). Note the inclusion on the left
side and exclusion on the right side.

The solution is simple: while the original random value happens to be zero,
generate another random number.

kind regards,

Jos
Reply


Similar Java bytes