简体   繁体   中英

Java Math.random period

I'm working on a big school project about random numbers, but I can't find the period for Math.random() . I have version 7.0.800.15 installed and I'm working an a windows 10 computer. I've tried determining the period with a simple program which saves the first values of:

double num = Math.random(); 

in an array and then loops until it finds the same values in a row again, thus a period would have passed, but with no result, the period is too long.

So my question is: What is the period of Math.random() on my version? Or: Is there a way to determine the period using a simple program?

Edit: took away a source pointing to a page about JavaScript, it was not relevant

Java's Math.Random uses a linear congruential generator with a modulus of 2^48. The period of such pseudorandom generator with well-chosen parameters is equal to the modulus. Apparently the parameters in Java are sanely chosen, so in practise the period is 2^48.

Sources: https://en.wikipedia.org/wiki/Linear_congruential_generator http://www.javamex.com/tutorials/random_numbers/java_util_random_algorithm.shtml#.WKX-gRJ97dQ

The wiki on linear congruential generator cites Java (java.util.Random) as having a modulus of 2 48 . That is likely the period but you may need to read more about these types of random generators.

This question ( How good is java.util.Random? ) also cites the same period.

Just to add to the other answers and to comment a little more generally on random number generators and writing a program to determine what the period is, beware of the Birthday Paradox and the Gambler's Fallacy . If you generate some value x , the next number is still just as likely to be x as any other number, and the number of numbers you need to generate before you're likely to have a duplicate is actually surprisingly small (meaning that you could, in principle, start seeing some duplicates before the end of the period, which complicates writing a program to test this).

The probability of a duplicate for probabilities up to 50% or so can be approximated by sqrt(2m * p(n)) where p(n) is the probability you're trying to calculating and m is the number of choices. For a 32-bit integer, sqrt(2m * p(n)) = sqrt(2 * 2^32 * 0.5) = sqrt(2^32) = 65,536 . There you have it - once you generate 65,536 numbers there's approximately a 50-50 chance you've generated a duplicate.

Once you've generated 2^32 + 1 values, the Pigeonhole Principle specifies that you must have generated at least one duplicate (assuming, of course, that you're generating a 32-bit number).

You may also be interested in this question on whether you can count on random numbers to be unique.

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