Win a copy of Functional Reactive Programming this week in the Other Languages forum!

Generating random Doubles between -1.0 and 1.0

tony cosgrave
Greenhorn
Posts: 3
Hi,

I know that to generate a random Integer between a certain range you can use .nextInt(maximum value) but having looked through the API there only seems to be a .nextDouble() and nextGaussian().

I'd be grateful if someone could explain how to I could generate a random Double between -1.0 and 1.0 please.

Thanks,

T

Campbell Ritchie
Sheriff
Posts: 50225
79
You call nextDouble, which give you a double value between 0.0 and 0.99999999999999999 approx, double it and subtract 1.0.

marc weber
Sheriff
Posts: 11343
Basically, the idea is to transform the output of the given methods. In general, multiply by some factor to transform the range, and then add/subtract to shift that range.

For example, nextDouble returns a value between 0.0 and 1.0. So if you wanted a value between -2 and 3, you could use...

double myDouble = (Random.nextDouble() * 5) - 2;
[ April 23, 2007: Message edited by: marc weber ]

tony cosgrave
Greenhorn
Posts: 3
That's spot on!