• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generating random Doubles between -1.0 and 1.0

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's spot on!

Thanks a million for your both your posts
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic