• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generating random Doubles between -1.0 and 1.0

 
tony cosgrave
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's spot on!

Thanks a million for your both your posts
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic