简体   繁体   中英

Java Random double in interval [-1000, 1000]

In java I have:

Random random = new Random();
double randomNum = random.nextDouble();

which creates a random number between 0 and 1. However I want a number between -1000 and 1000, how would I scale this?

Thanks

2 possibilities:

  1. [less dense]: multiple your results by 2000, and subtract 1000 from the result. It won't be as 'dense' as possibility 2.
  2. get a random int in range [-1000,999], and add a random double in range [0,1].

Note that possibility 2 ensures better randomness and better 'density' of your numbers, at the cost of 2 random calls [which might be expansive, if it is an issue].

嗯,数学?

double randomNum = (random.nextDouble()-0.5d) * 2000;
Random random = new Random();
double randomNum = (random.nextDouble() * 2000.0d) - 1000.0d;
 public  static double randomInterval(double minValue,double maxValue){
    Random random = new Random();
    double r;
    do {
        r = random.nextDouble();
    } while (r < minValue || r >= maxValue);
    return r;
}

Example :

double a = randomInterval(-1000,1000) ;

Try this algorithm:

  1. Generate a random value in the range 0 to 1.
  2. multiply that value by 2000 (the size of the desired range).
  3. subtract 1000 from the result of step 2 (move the value into the desired range).

这会为您提供该范围内的数字

double randomNum = (random.nextDouble() * 2000) -1000;
Random random = new Random();
int randomNum = random.nextInt(2000) - 1000;

Here is a general function you could use to linearly rescale a number between zero and one ( val01 ) to a different range ( min .. max ):

    public static double rescale(double val01, double min, double max) {
        return val01 * (max - min) + min;
    }
public static double doubleBetween(double start, double end) {
    Random random = new Random();

    // We need 64 bits because double have 53 bits precision, so int is too short
    // We have now a value between 0 and Long.MAX_VALUE.
    long value = -1L;
    while (value < 0)
      value = Math.abs(random.nextLong()); // Caution, Long.MIN_VALUE returns negative !


    // Cast to double
    double valueAsDouble = (double) value;

    // Scale so that Long.MAX_VALUE is exactly 1 !
    double diff = (end-start)/(double) Long.MAX_VALUE;


    return start + valueAsDouble*diff;
}

This will give the correct interval including both ends with full double precision. doubles have a special -0.0 value (the negative zero) which will not be given by this routine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM