Java random intersection in range: unexpected results

Please consider this piece of code:

private static final Random RANDOM = new Random();

    public static void main(String[] args) {

        long distinct = IntStream.range(0, 600)
                .map(i -> RANDOM.nextInt(600))
                .distinct()
                .count();

        System.out.println("intersection %:" + (double) (600 - distinct) / 600 * 100);
    }

      

I am generating a random int in the range (0-600) 600 times, naively expecting a 0% intersection. Real results ~ 37%.

Is there a mathematical formula for calculating the probability of intersection that has a range of random numbers and a number of calls? I don't really like to trust this empirical 37% on my calculations

+3


source to share


1 answer


Java is Random.nextInt()

guaranteed to have a uniform distribution and not be unique every time you call it.

So the probability of intersection is the same calculation as the birthday problem ( https://en.wikipedia.org/wiki/Birthday_problem ). I wish I had the whole formula above, but it can be found easily with a little research (or even calculation).



EDIT2:

The wikipedia page already had everything you need: Look at the part collision counter.

+3


source







All Articles