Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2006

Tip: Looking for answers? Try searching our database.

Generating Random Numbers between a potentially negative range

Thread view: 
laura.paterson@gmail.com - 08 Feb 2006 11:50 GMT
Hi,

I have looked in the existing posts to try to find the solution to
this, but cannot find an answer...

I want to be able to create a random number within a certain range,
that may be partially or entirely negative, i.e. between 17 and 25, -17
and 25, -25 and 25... etc.

I have found various solutions using Math and Random, which would work
if both limits are either positive or negative, or if they are the same
distance form the origin, ie. -25, 25... but nothing that will work for
all range possibilities.

Any help will be much appreciated!
Thanks,
Laura
Bart Cremers - 08 Feb 2006 12:01 GMT
   public static int nextInt(int low, int high) {
       if (low > high) {
           int tmp = low;
           low = high;
           high = tmp;
       }

       int diff = high - low;

       int i = rnd.nextInt(diff);

       return i + low;
   }
Boris Stumm - 09 Feb 2006 09:04 GMT
>     public static int nextInt(int low, int high) {
>         if (low > high) {
[quoted text clipped - 9 lines]
>         return i + low;
>     }

How about:
import static java.lang.Math.*;

public static int nextInt(int low, int high) {
       return min(low, high) + rnd.nextInt(abs(high - low));
}
Roedy Green - 08 Feb 2006 17:53 GMT
>I want to be able to create a random number within a certain range,
>that may be partially or entirely negative, i.e. between 17 and 25, -17
>and 25, -25 and 25... etc

see http://mindprod.com/jgloss/pseudorandom.html#LOWHIGH
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.