allen501pc / jlibs

Automatically exported from code.google.com/p/jlibs
0 stars 0 forks source link

overflow not handled in random functions #46

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
For example, create random double number with min == -Double.MAX_VALUE and
max == Double.MAX_VALUE

or a random integer with min == -10 and max = Integer.MAX_VALUE - 3

What is the expected output? What do you see instead?
One expects a number in the specified range, but
the range calculation overflows (since the maximal values are used).

What version of the product are you using? On what operating system?
I am using the version currently in the source code archive.

Please provide any additional information below.

A possible solution for doubles is provided below, which you can use under the 
LGPL license of jlibs, when credentials are included.

 /** @author Pierre van de Laar - TNO-ESI
   */
   public static double random(double min, double max){
        final double factor = 4;
        if (min < Double.MAX_VALUE/-factor || max > Double.MAX_VALUE/factor)
        {
            //Prevent overflow with large ranges 
            final double mindivfactor = min/factor;
            final double retval = factor * ( mindivfactor + Math.random()*((max/factor)-mindivfactor) );
            return retval;
        } 
        else 
        {
      final double retval = min+Math.random()*(max-min);
      return retval;
    }                   
    }

Original issue reported on code.google.com by Pierre.v...@gmail.com on 3 Dec 2013 at 1:44