aspose file tools*
The moose likes Beginning Java and the fly likes Generating random Doubles between -1.0 and 1.0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generating random Doubles between -1.0 and 1.0" Watch "Generating random Doubles between -1.0 and 1.0" New topic
Author

Generating random Doubles between -1.0 and 1.0

tony cosgrave
Greenhorn

Joined: Nov 15, 2003
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

Joined: Oct 13, 2005
Posts: 39436
    
  28
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

Joined: Aug 31, 2004
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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
tony cosgrave
Greenhorn

Joined: Nov 15, 2003
Posts: 3
That's spot on!

Thanks a million for your both your posts
 
wood burning stoves
 
subject: Generating random Doubles between -1.0 and 1.0