Java Random Numbers Using a Seed

Java random numbers using a seed

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic
random bit generator DRBG, is an algorithm for generating a sequence
of numbers that approximates the properties of random numbers. The
sequence is not truly random in that it is completely determined by
a relatively small set of initial values, called the PRNG's state,
which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
return generator.nextDouble()*0.5;
}

How does java Random() find a seed?

Java used to use the system time as the default seed, up to 1.4.2. In 1.5 this "bug" was fixed. Compare the 1.4.2 API specification:

Creates a new random number generator. Its seed is initialized to a value based on the current time:

public Random() { this(System.currentTimeMillis()); }

Two Random objects created within the same millisecond will have the same sequence of random numbers.

With the 1.5 API specification:

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

The current implementation in OpenJDK uses a static AtomicLong which is updated every time you create a new Random instance without a seed. If you don't have the source code locally, you can find it in the source code on github:

    public Random() {
this(seedUniquifier() ^ System.nanoTime());
}

private static long seedUniquifier() {
// L'Ecuyer, "Tables of Linear Congruential Generators of
// Different Sizes and Good Lattice Structure", 1999
for (;;) {
long current = seedUniquifier.get();
long next = current * 1181783497276652981L;
if (seedUniquifier.compareAndSet(current, next))
return next;
}
}

private static final AtomicLong seedUniquifier
= new AtomicLong(8682522807148012L);

How do I create a java random number generator that creates 3 numbers using seeds?

In java random numbers can be produced using class Random.For example:

Random randomNumbers=new Random();
int random=randomNumbers.nextInt();

This generates a random number from –2,147,483,648 to +2,147,483,647.
In the above code, no seed value is given. So the program uses the current system time in milliseconds as the seed value.Thus the above statement is equivalent to:

Random randomNumbers=new Random(System.currentTimeMillis());

A specific seed always generates a identical set of random numbers.Since the time keeps changing, the sequence generated using the time of day as a seed always gives a unique set of random values.

Now how to generate random numbers within a certain range?
The statement:

Random randomNumbers=new Random(2);
int random=randomNumbers.nextInt(8);

generates a random number from 0 to 7 using the seed value 2 which we can off course make an user to input.The value 8 is called scaling factor. But in most of the cases we have to shift these values in order to get he desired output.So the random numbers generated above should be shifted by 1. Thus we write a expression:

int randomNum=1+randomNumbers.nextInt(8);

Now it generates random numbers in the range 1 to 8.

In order to generate 3 random numbers in a sequence you can use a loop.

for(int i=0;i<3;i++){
int random=1+randomNumbers.nextInt(8);
System.out.println(random);
}

random number with seed

Since you asked for an example:

import java.util.Random;
public class RandomTest {
public static void main(String[] s) {
Random rnd1 = new Random(42);
Random rnd2 = new Random(42);

System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
}
}

Both Random instances will always have the same output, no matter how often you run it, no matter what platform or what Java version you use:

30 - 30
234785527 - 234785527
0.6832234717598454 - 0.6832234717598454
5694868678511409995 - 5694868678511409995

Seed, Random number, and bound using java.uitl.Random

A seed is not necessarily the first number in the sequence of random-numbers generated by a PRNG. The seed is only used to initialize the random-number generator, which is pseudo random. Basically the "pseudo" means that numbers aren't random at all, but simply looking random. They're just generated by a (more or less) complex function from previously generated numbers. The purpose of the seed is to be used as a starting point, from which the PRNG can start to create numbers. Whether the sequence starts with the seed as first output-number or doesn't is rather implementation-specific, though for simple security-reasons it's recommendable not to start with the seed as first output-number.

Note that two PRNG using the same code and seed produce the exact same sequence of numbers - there might be some coincidental sideeffects that alter the result though.

As an example for what a seed is used for in a PRNG, take a look at this implementation of XORShift, which is a rather simple PRNG:

class XORShift{
private int x, y, z, w;

public XORShift(int seed){
x = seed;
y = seed >>> 20 | seed << 12;
z = seed >>> 10 | seed << 22;
w = seed >>> 25 | seed << 7;
}

public int next() {
int t = x;
t ^= t << 11;
t ^= t >> 8;
x = y; y = z; z = w;
w ^= w >> 19;
w ^= t;
return w;
}
}

As you can see, the seed is used to initialize the state-variables of the generator, which are then altered in each step and combined to produce a new random number. The above algorithm is just a translation of the example-code on wikipedia into java, you'll find pretty much the same code in c/c++ there.

What is seed in util.Random?

A pseudo-random number generator produces a sequence of numbers. It
isn't truly random, but generally a mathematical calculation which
produces an output that matches some desirable distribution, and
without obvious patterns. In order to produce such a sequence, there
must be state stored for the generator to be able to generate the next
number in that sequence. The state is updated each time using some
part of the output from the previous step.

Seeding explicitly initialises this state. A 'seed' is a starting
point, from which something grows. In this case, a sequence of
numbers.

This can be used either to always generate the same sequence (by using
a known constant seed), which is useful for having deterministic
behaviour. This is good for debugging, for some network applications,
cryptography, etc.

Or, in situations where you want the behaviour to be unpredictable
(always different each time you run a program, a card game perhaps),
you can seed with a number likely to be continually changing, such as
time.

The 'randomness' of the sequence does not depend on the seed chosen,
though it does depend on not reseeding the sequence.

Taken from What is a seed in relation to a random number generation algorithm and why is computer time used to create this seed more often than not?

This should answer your question.

How to generate random numbers using a seed, and populating a 2D array with them

You may use System.out.printf

for (double[] d : tab) {
for (double n : d) {
System.out.printf("%.2f\t", n);
}
System.out.println();
}

Result

0,73    0,09    0,49    
0,46 0,45 0,70
0,28 0,76 0,22

java-8

If you're using java-8, you may want to look at the following code for generating arrays of random numbers.

  • Stream.generate : Generates a stream. Takes a Supplier as parameter. Here we gave it () -> r.doubles(3).toArray() which basically means : With the random object, generate 3 random doubles and return an array.
  • limit(3) : Limits the number of arrays returned by Stream.generate to 3
  • toArray(double[][]::new) : As it is a stream of double[] that we created before, we want to have a new array containing those objects, so what we are doing here is creating an array of double[]. So, a double[][] and it is the terminal operation of this stream pipe.

int seed = 5;
Random r = new Random(seed);
double[][] tab = Stream.generate(() -> r.doubles(3).toArray())
.limit(3)
.toArray(double[][]::new);

See also

How can I generate different random numbers using a seed with a loop?

Place your instance of Random outside the loop. What you're doing is creating a new instance of random each iteration, with the same seed. The seed determines which values are going to get generated, and with the same seed, you'll get the same numbers each time.



Related Topics



Leave a reply



Submit