Math.random () follows which algorithms

We use the method math.random()to generate random numbers. but I doubted this method. math.random () - which algorithms will fall to generate random numbers. Is there any other random number generated algorithm?

I am trying to execute this code, but I think it is inefficient for generating random code:

for (int i = 0; i < N; i++) {
     int sd = i + (int) (Math.random() * (N-i));

     String t = one[r];
     one[r] = one[i];
     one[i] = t;
 }

Is there a better random number generation algorithm?

+4
source share
5 answers

Use java.util.RandomAPI

. 48- , . (. , " ", 3, 3.2.1.)

: , PRNG. .

: Math.random() java.util.Random

+2

, ,

String[] words = ...
Collections.shuffle(Arrays.asList(words));

, . , Random .

Random rand = new Random();
for (int i = words.length - 1; i > 0; i--) {
     int sd = rand.nextInt(i+1); // random number between 0 and i inclusive

     String t = words[r];
     words[r] = words[i];
     words[i] = t;
}
+1

Java API .

java.lang.Math.random()

Math-, :

private static Random randomNumberGenerator;

private static synchronized void initRNG() {
    if (randomNumberGenerator == null)
        randomNumberGenerator = new Random();
}

public static double random() {
    if (randomNumberGenerator == null) initRNG();
    return randomNumberGenerator.nextDouble();
}

Math.random() - Random Class. , java.util.Random, .

java.util.Random

Random .

LCG - . java.util.Random , . ( ), .

java.util.Random (, ,...), - , java.security.SecureRandom.

java.util.Random , . , ThreadLocalRandom.

java.security.SecureRandom

SecureRandom java.util.Random . SecureRandom .

SecureRandom ( ).

java.security.SecureRandom , java.util.Random - .

java.util.concurrent.ThreadLocalRandom

ThreadLocalRandom Linear Congruential Generator, , .

, java.util.Random .


java.util.Collections.shuffle(list) java.util.Random , java.security.SecureRandom.

+1

:

1:

2: Java Collection.shuffle()

, , .

java : java.util.Random java.lang.Math.random. java.lang.Math.random() java.util.Random. .

0

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


All Articles