Java 7 random class

Why generator.nextDouble()in java returns values ​​only in the range from 0 to 1? The method generator.nextInt()requires a limit value. Why is this not the case with the method Double?

+4
source share
4 answers

This answer is a bit speculative, but I assume that the reason for this is because the random number generator should return uniformly evenly. There is nothing common in generating doubles evenly, because the doublets themselves are not evenly distributed.

Ignoring signs, doubles, or floating-point numbers is generally preserved in the form m * 2^e, where mthey ehave a fixed bit width, where it is minterpreted as a number between 0(inclusive) and 1(exception). This means that for large numbers the difference between two consecutive doubles is much greater than for small numbers. Thus, simply filling a double with random bits will not result in uniformly distributed pseudorandom numbers.

Instead, the solution is to fix the exponent eto 0 and select only a random mantissa mthat gives an evenly distributed double bond between 0 and 1. If you need random doubling in another range, you can multiply the number with the desired range:

double randomDouble = rng.nextDouble() * range;

, .

+2

, 0.0 1.0 : 0.0 1.0. , Random :

public double nextDouble(double min, double max) {
    return min + nextDouble() * (max - min);
}

, . , nextDouble() , "".

Hoopje: , 0.0 1.0 , .

(: ) IEEE 754, , , .

IEEE- 0.0, 1.0 1.70141 * 10 ^ 38, ( float - double):

0.0          =  0x00000000 = 0
1.0          =  0x3F800000 = 1065353216
1.7...*10^38 =  0x7EFFFFFE = 2130706430

, 0.0 1.0 , 1.0 170141163178059628080016879768630000000.0. , , , , .

, 0.0 1.0 , . , , "" ...

+2

API. , , , ( ).

, nextDouble() PRNG .

, API-, Java ( ) FP-. , . , API.

+1

, :

double max = 100000; // just an example
double randomDouble = (new Random()).nextDouble() * max;

Theoretically, I think there are no good reasons why they cannot provide a method like the one below. I think this was not provided simply because the above idiom is simple enough and no one complained :-)

/**
 * Return a pseudorandom, uniformly distributed double value between
 * 0 (inclusive) and the specified <code>max</code> value (exclusive)
 * drawn from this random number generator sequence.
 * @param max
 * @return
 */
double nextDouble(double max);
0
source

Source: https://habr.com/ru/post/1664473/


All Articles