Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many times can I use randomGenerator.nextDouble() before I need to reseed?

Tags:

java

random

I'm using the Random class in Java as a pseudo-random number generator. I'm using the function nextDouble a lot of times (~10^5). How many times before I have to reseed to prevent from getting the same numbers? Is reseeding needed?

    Random generator = new Random();
    double[] numbers = new double[n];
    for (int i = 0; i < n; i++) numbers[i] = generator.nextDouble();

This is for an experiment, the numbers will be used as coordinates for points on a space, so I want the distribution to be as uniform as possible.

Also how do I reseed? Where do I get the int seed from?

like image 293
Uri Avatar asked Apr 18 '12 19:04

Uri


People also ask

What is random nextDouble?

nextDouble. Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

How does the random class work?

Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int.

Is Java random really random?

Java Random Generation - JavaBitsNotebook.com. Computers can be used to simulate the generation of random numbers. This random generation is referred to as a pseudo-random generation. These created values are not truly "random" because a mathematical formula is used to generate the values.

What is the use of import Java Util random?

Random class is part of java. util package. An instance of java Random class is used to generate random numbers. This class provides several methods to generate random numbers of type integer, double, long, float etc.


2 Answers

The random number generator will produce a random double from two random int values. The internal seed has 48 bit, so the random sequence repeats after at most 2^48 int values, or 2^47 double values.

like image 163
Christian Semrau Avatar answered Sep 28 '22 02:09

Christian Semrau


You don't need to worry about reseeding etc if you use a Set (which guarantees unique values):

Random generator = new Random();
Set<Double> numbers = new HashSet<Double>();
while (numbers.size() < n)
    numbers.add(generator.nextDouble());

Despite what you might think, this executes quite quickly: 60 milliseconds for 100000 numbers on a my (typical) PC.

If you really want an array, you can extract it from the set.
If you want to maintain the order they were generated in, use a LinkedHashSet (it had similar performance)

like image 41
Bohemian Avatar answered Sep 28 '22 03:09

Bohemian