• 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

Generate Random Number within a range including negatives?

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have no idea how to generate a random number within a given range. The range can include negative numbers. Can anyone help?
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why not subtract a fixed number from a random number? If you need more or less range, multiply by some suitable number.
 
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
Math.random() is a good place to start. If that doesn't suit your needs, then java.util.Random should be your next stop.

Math.random() generates a double between 0 and 1 (including 0, but not 1). As T Dahl suggested, you can multiply this value by some factor to increase your range, then shift that range by adding or subtracting.
 
Sheriff
Posts: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In general, for any function f that returns a value between a and b, to get a value between c and d apply the following calculation: (f(x) - a) / (b - a) * (d - c) + c.

The subtraction of a gives you a value between 0 and (b - a).
The dividing by (b - a) gives you a value between 0 and 1 (provided b != a).
The multiplication gives you a value between 0 and (d - c).
The addition of c gives you a value between c and d.

In this case, a == 0 and b == 1, so you are left with Math.random() * (d - c) + c.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic