Вопрос

I am wondering why the code below, using the Mersenne Twister (in java), always gives the same 99 numbers no matter how many times I run it. In essence it isn't random?

    MersenneTwister mt = new MersenneTwister();
    for(int i = 0; i<=99; i++ ) {
        System.out.println("Next "+mt.nextDouble());
    }
Это было полезно?

Решение

tl;dr: Change your new MersenneTwister() to new MersenneTwister(new Date()) instead.

Pseudo-random number generators use a seed to determine the sequence of numbers that come out. Generators will set a seed by default if you don't set one. Some generators use a different seed by default each time, such as by using your computer's clock, or by reading from /dev/urandom. Others will use a fixed seed by default.

It sounds like your generator is using a fixed seed by default (MersenneTwister()'s documentation says "Constructs and returns a random number generator with a default seed, which is a constant" [emphasis in original]). This will, of course, result in the same stream of numbers.

You should use either the MersenneTwister(Date) constructor (just use new MersenneTwister(new Date())), or the MersenneTwister(int) one (though that seems less ideal, since int is only 32 bits wide).

Другие советы

Mersenne Twister is a algorithm to create predictable, randomly, equal distributed numbers from a Seed. In your case you need to feed the Twister with a seed like the systems time or better a source of randomness that the underlying OS provides.

The Mersenne Twister only mixes around bytes, so you will always get the same results from the same seed. This is good to create for example virtual worlds in a game where you can recreate gigabytes of data with just one small seed. It is not a way to create randomness, but a way to create randomly distributed values from a seed (that can be a random value or a predictable value like a date).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top