0

Will I get better random numbers quality if I will use such solution?

import java.util.*;

public class Main {
    private static final Random PRNGs[] = new Random[137];

    private static int nextInt() {
        return PRNGs[ (int)(System.currentTimeMillis() % PRNGs.length) ].nextInt();
    }

    static {
        for(int i=0; i<PRNGs.length; i++) {
            PRNGs[i] = new Random();
        }
    }

    public static void main(String[] args) {
        System.out.println( nextInt() );
    }
}

We know that in the real life it is possible to have 12 times red (or black) on the roulette. If one single instance of Random object is used such event as 12 times the same color is not achievable.

Todor Balabanov
  • 376
  • 3
  • 6
  • 17
  • 6
    "If one single instance of Random object is used such event as 12 times the same color is not achievable." How did you come up with that assumption? – Kayaman Oct 11 '17 at 09:05
  • 5
    What do you mean by "better"? When talking about random number generators, you worry about distribution and deviation (see https://stackoverflow.com/questions/6011943/java-normal-distribution for example). In other words: you should clarify your requirements - not sure what exactly you are asking for. – GhostCat Oct 11 '17 at 09:05
  • 4
    `PRNGs[i] = new Random();` is *evil*: all generators will be initialized by system timer and that's why will have the *same seed*. – Dmitry Bychenko Oct 11 '17 at 09:05
  • GhostCat Better in the sense of better result in Die Hard test for example. Dmitry Bychenko Do Oracle use milliseconds for Random object initialization? – Todor Balabanov Oct 11 '17 at 09:09
  • No, you will not get better randomness. If you did, it would solve a lot of problems in a simple way (who needs a HWRNG if you can just chain a bunch of software ones together). Your initial assumption of "not getting 12 times the same color with a single `Random`" is also complete hogwash. – Kayaman Oct 11 '17 at 09:17
  • You're just wasting time and memory, and it's quite possible that your final result will be LESS random than just using the PRNG as it was designed. Don't try to be clever with RNGs or crypto. Just use as documented. If the PRNG is a reasonable one, run 1 million spins: you should get 12 reds in a row about 244 times. – Lee Daniel Crocker Oct 11 '17 at 17:51

1 Answers1

1

No, you do not get any better randomness. Have a look at SecureRandom If you want to use the random values e.g. for encryption. Random is quite predictable, whereas SecureRandom is not (that is the difference).

„Real“ random numbers need hardware support and are, to my knowledge, not readily available in Java.

As for „12 times red in a row“: the chances are very slim (assuming a 50/50 chance for red or black): 1/0.5^12 (1 in 4096) tries will give you 12 times red in a row.

Jens
  • 570
  • 3
  • 11