What is random seed about? - java

For example the code below. It has a random class. However it always produce the same output everywhere . In this case which item is the seed?
source: link
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());
}
}

42 is the seed, as the very same Javadoc says. So, what is a seed? A random number is seldom truly random - often it's a pseudo-random instead. This means it's generated from a function, which is said PRNG (pseudo random number genrator). Being generated from a function, in turn, means that the output is not random anymore, since it's predictable!
However, depending on your needs, this pseudo-randomness may be enough - I said enough because generating random bit is expensive, and I'm not talking about time or memory, but about money (see this link on wikipedia). So, for example, if you need a random value to place enemies in your game, a pseudo-random number is ok - but if your are building security-related software, you want to use a true random number, or at least a cryptographically secure PRNG.
How can we describe a PRNG, like the one used in Math.random()? It's a function, initialized with a seed S that returns an array of values A. Note that, for each integer S, is defined one and only one array A. For example (values are not actual):
first call second call third call
seed: 14329 .18 .82 .5
seed: 3989 .7 .02 .93
So you seed you PRNG with some known value when you want its result to be predictable - for example for testing purposes or to ensure that, each time you run level 1 in your game, the enemies are always placed in the same (pseudo) random places - otherwise you don't need to explicitely pass a seed.

Random Seed on Wikipedia:
A random seed (or seed state, or just seed) is a number (or vector)
used to initialize a pseudorandom number generator.
In other word, it is the number from which a seem-to-be-random sequence will be generated. Therefore, if you use the same number, the senquence will always be the same.
In practice, we usually use System Time as seed.

The seed is given as the argument of the constructor of Random; using the same seed will yield the same sequence of numbers. However this is discussed under the link in thet question.

In this case the seed is 42. This is the reason for the same output - you use the same seed.
You can use for example
Random rnd1 = new Random(System.currentTimeMillis())
for different outputs.

The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).
The invocation new Random(seed) is equivalent to:
Random rnd = new Random();
rnd.setSeed(seed);

From the Java documentation in the Random class
Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).
The invocation new Random(seed) is equivalent to:
Random rnd = new Random();
rnd.setSeed(seed);
So 42 is the seed given to the new Random() in your example

Related

Unique random - srand in java ? (like in c++)

Currently I'm using a
Random rand = new Random();
myNumber = rand.nextInt((100-0)+1)+0;
and it's a pseudo-random, because I always get the same sequence of numbers.
I remember in c++ you could just use the ctime and use srand to make it unique. How do you do it in java ?
If you require a unique random in Java, use SecureRandom. This class provides a cryptographically strong random number generator (RNG), meaning it can be used when creating certificates and this class is slow compared to the other solutions.
If you require a predictable random that you can reset, use a Random, where you call .setSeed(number) to seed it to make the values predictable from that point.
If you want a pseudo-random that is random every time you start the program, use a normal Random. A random instance is seed by default by some hash of the current time.
For the best randomness in every solution, it is important to RE-USE the random instance. If this isn't done, most of the output it gives will be similar over the same timespan, and at the case of a thrown away SecureRandom, it will spend a lot of time recreating the new random.

Why this code is giving strange result? So Random?

I have piece of code which generates some Random number and prints out on console. However I am curious about the pattern which it prints, Such as,
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Random random = new Random(-6732303926L);
for(int i=0;i<10;i++)
System.out.println(random.nextInt(10)+" ");
}
}
Result : 0 1 2 3 4 5 6 7 8 9 - Every number in new line.
And if you change this code a bit! like,
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Random random = new Random(-6732303926L);
for(int i=0;i<10;i++)
System.out.println(random.nextInt(11)+" ");
}
}
Result : 8 9 2 2 10 3 8 7 0 10 - Every number in new line.
What is the reason of 0123456789 which is not random at all!?
0123456789 is random too, in this case - it's about as likely to come up as 14235682907, which would no doubt not have given you any cause for concern.
You spotted a fluke, basically. If you print the next 10 numbers in the first case, they're not preserving any obvious order.
It's like flipping a coin - the pattern HHHHHHHH is just as likely to come up as the exact pattern HHTHTTHH; there's a 1 in 28 chance of each coming up, as at any of the 8 steps there's a 50% chance of it going wrong. But the first pattern looks like it's broken, whereas the second doesn't.
I think it is random... you are using a specific seed for the random function. You just found the seed that will give you the numbers 0 - 9, in order.
EDIT: Apparently, this is the algorithm:
The java.util.Random class implements what is generally called a linear congruential generator (LCG). An LCG is essentially a formula of the following form:
numberi+1 = (a * numberi + c) mod m
Source: here
The Random class is a pseudo-random number generator. Thus it is not truely random, but instead relies on mathematical operations performed on an initial seed value. Thus, certain seeds will produce certain (potentially interesting/fun) sequences
The reason for the sequence is so that one can test software by making Random predicable with predictable and repeatable sequences using its next methods. Whenever a particular long seed parameter is a parameter to the Random constructor, the instanced Random object is supposed to return the same sequences of values through its next methods. This is a deliberate feature of java.util.Random.
java.util.Random has two constructors:
Random()
and
Random(long seed)
The constructor without a long integer seed uses the system time for creating a seed value for the pseudo random number generator. No two instantiations of Random will use the same seed and you should get a very good pseudo-random sequence. A Random instantiation using the constructor without a seed creates an instance with unpredictable sequences of values that will be pseudo-random.
The constructor with a seed value is intended only for making Random deterministic with predictable sequences using its next methods. The typical use of a seed is for software test purposes where results must be predicable and repeatable. Every instance of Random that uses the same long seed integer will create the same sequence of results every time. The particular long you used causes the sequence to be 0 1 2 3 4 5 6 7 8 9 over and over again when getting one of 10 integer values using nextInt(10) method. This and other predictable sequences that are repeatable every time software executes are very useful for testing software and are not meant for creating unpredictable pseudo-random sequences.
Creating random with a seed ensures a certain behavior. Especially, creating two instances of Random with the same seed, will always behave identically. Someone found out (via brute force, I guess) that using this particular seed together with the first 10 nextInt(10), creates such a seemingly ordered sequence. This sequence is pseudo-random updon first creation, but can be reproduced. Changing anything in the slightest gives a different result.
Random is based on the seed you give to it, if you want to get true random numbers, use time functions as seeds, and you'll get a real random number series.

Java random always returns the same number when I set the seed?

I require help with a random number generator I am creating. My code is as follows (inside a class called numbers):
public int random(int i){
Random randnum = new Random();
randnum.setSeed(123456789);
return randnum.nextInt(i);
}
When I call this method from another class (in order to generate a random number), it always returns the same number. For example if I were to do:
System.out.println(numbers.random(10));
System.out.print(numbers.random(10));
it always prints the same number e.g. 5 5. What do I have to do so that it prints two different numbers e.g. 5 8
It is mandatory that I set the seed.
Thanks
You need to share the Random() instance across the whole class:
public class Numbers {
Random randnum;
public Numbers() {
randnum = new Random();
randnum.setSeed(123456789);
}
public int random(int i){
return randnum.nextInt(i);
}
}
If you always set the seed, you will always get the same answer. That is what setting the seed does.
There are two issues causing what you see. The first is that the code sets a seed value for a Random instance. The second is that the instance method "random" instances a new Random object and then immediately sets its seed with the same seed every time. The combination of these two guarantees that, for the same value of i, the method "random" will always return the same value and it will always be the first in the sequence that the seed always generates.
Assuming setting the seed is mandatory, to get the next value in the sequence instead of the same first value of the sequence every time, the randnum instance of Random can't have its seed set every time just before its next method gets called. To fix that, move the randnum local variable instance of Random from the scope of the random instance method to the class scope. Second, set the seed only when random is assigned a Random instance or only to get same sequence of results from it to start over again. Class Random's setSeed(long seed) instance method can't execute in the class scope, so the constructor has to set it using the Random constructor with the long seed parameter. The following code shows the changes:
public class RandomDemo { // arbitrary example class name
// lots of class related stuff may be here...
// still inside the class scope...
// private is a good idea unless an external method needs to change it
private Random randnum = new Random(123456789L);
// the seed guarantees it will always produce the same sequence
// of pseudo-random values when the next methods get called
// for unpredicable sequences, use the following constructor instead:
// private Random randnum = new Random();
// lots of code may be here...
// publicly exposed instance method for getting random number
// from a sequence determined by seed 123456789L
// in the range from 0 through i-1
public int randnum(int i) {
// don't set the seed in here, or randnum will return the exact same integer
// for the same value of i on every method call
// nextInt(i) will give the next value from randnum conforming to range i
return randnum.nextInt(i);
} // end randnum
// lots of more code may be here...
} // end class RandDemo
The above will give you an exact solution to your exact problem, as stated. However, using a mandatory seed seems unusual, given what it does.
If this is for a class project or software testing where the sequence has to be predictable and repeatable, setting the seed to a fixed value makes sense. Otherwise, question the validity of setting the seed to some predetermined value. The following explains more about Random, seeds for Random and why there is a provision for supplying a seed.
Random has two constructors:
Random()
and
Random(long seed)
and an instance method
setSeed(long seed)
that all affect the sequence of numbers obtained from a Random instance. The instance method,
setSeed(long seed)
sets the Random object to the same state it would have been in had it been just instanced with the same seed as the constructor argument. Only the low-order 48 bits of a seed value get used.
If a Random object is instanced without a seed, the seed will be the same as the system time in milliseconds. This ensures that, unless two Random objects are instanced in the same millisecond, they will produce different pseudo-random sequences. Only the low order 48 bits of the seed value gets used. This causes unpredictable pseudo-random sequences. It is not necessary and wasteful of computing resources to get a new instance of Random every time one calls a next method.
Random's seed parameters are provided so that one may instance a Random object that produces a sequence that is repeatable. For a given seed, the sequence of values in next methods are guaranteed to be the same sequence whenever that seed is used. This is useful for testing software that is going to use pseudo-random sequences where results have to be predicable and repeatable. It is not useful for creating different unpredictable pseudo-random sequences in operation.
The statement "it is mandatory that I set the seed" negates any unpredictablity of the Random object's pseudo-random sequences. Is this for a class project or software test where results have to be the same for the same inputs to the program?
Set the seed once on startup, rather than every time you want a new random number.
What you are using is not a Random Number Generator, it's a Pseudo-Random Number Generator. PRNG's generate sequences of pseudo-random numbers, the seed selects a starting point in a sequence (a PRNG may generate one or several sequences).
Do you necessarily need to create the new Random() inside your random(int i) method? If you are OBLIGED to do it that way, you could use, you could set the seed to the current time, although that is not fail proof, because you could call your numbers.random(10) so fast after the other that it would end up being the same seed. You could try maybe using nanoSeconds (System.nanoTime() I think? And if setSeed only accepts int, multiply it I guess).
What I would suggest however, if you are allowed to do so, is to declare your Random outside your method. If you instanciate your random variable in, say, your number class constructor, you could set any seed and any time you call your method it would give you a new number. (They will be the same sets of numbers every time you restart your application if you use a constant seed however, you could use time as your seed in this case too).
Finally, the last problem could be if you declare several number classes at the same time. They will all have the same random seed and give you the same set of random numbers. If this happens, you can make a static Random in your main class, and call it in your numbers class. This will couple those two classes though, but it would work. Another option would be to send an incrementing value to your number class constructor, for each number you instanciate, and use the value you pass as the seed.
The second option should be good for you though, if you are allowed to do it that way.
Usually, Random is not truly random but pseudorandom. It means it takes a given seed and uses it to generate a sequence of numbers that looks like random (but is enterely predictable and it repeats if you put the same seed).
If you don't put seed, then the first seed will be taken from a variable source (usually the system time).
Usually, a value with seed will be used in order to have it repeat the exact values (for example, for testing). Use Random without seed instead.

Uniform distribution with Random

I know if i use the Random generator from Java, generating numbers with nextInt, the numbers will be uniformly distributed. But what happens if I use 2 instances of Random, generating numbers with the both Random classes. The numbers will be uniformly distributed or not?
The numbers generated by each Random instance will be uniformly distributed, so if you combine the sequences of random numbers generated by both Random instances, they should be uniformly distributed too.
Note that even if the resulting distribution is uniform, you might want to pay attention to the seeds to avoid correlation between the output of the two generators. If you use the default no-arg constructor, the seeds should already be different. From the source code of java.util.Random:
private static volatile long seedUniquifier = 8682522807148012L;
public Random() { this(++seedUniquifier + System.nanoTime()); }
If you are setting the seed explicitly (by using the Random(long seed) constructor, or calling setSeed(long seed)), you'll need to take care of this yourself. One possible approach is to use a random number generator to produce the seeds for all other generators.
Well, if you seed both Random instances with the same value, you will definitely not get quality discrete uniform distribution. Consider the most basic case, which literally prints the exact same number twice (doesn't get much less random than that ...):
public class RngTest2 {
public static void main(String[] args) throws Exception {
long currentTime = System.currentTimeMillis();
Random r1 = new Random(currentTime);
Random r2 = new Random(currentTime);
System.out.println(r1.nextInt());
System.out.println(r2.nextInt());
}
}
But that's just a single iteration. What happens if we start cranking up the sample size?
Here is a scatter plot of a distribution from running two same-seeded RNGs side-by-side to generate 2000 numbers total:
And here is a distribution of running a single RNG to generate 2000 numbers total:
It seems pretty clear which approach produced higher quality discrete uniform distribution over this finite set.
Now almost everyone knows that seeding two RNGs with the same seed is a bad idea if you're looking for high quality randomness. But this case does make you stop and think: we have created a scenario where each RNG is independently emitting fairly high quality randomness, but when their output is combined it is notably lower in quality (less discrete.)

random number with seed

Reference: link text
i cannot understand the following line , can anybody provide me some example for the below statement?
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers
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
The random generator is deterministic. Given the same input to Random and the same usage of the methods in Random, the sequence of pseudo-random numbers returned to your program will be the same even in different runs on different machines.
This is why it is pseudo-random - the numbers returned behave statistically like random numbers except they can be reliably predicted. True random numbers are unpredictable.
The Random class basically is a Psuedorandom Number Generator (also known as Deterministic random bit generator) that generates a sequence of numbers that approximates the properties of random numbers. It's not generally random but deterministic as it can be determined by small random states in the generator (such as seed). Because of the deterministic nature, you can generate identical result if you the sequence of methods and seeds are identical on 2 generators.
The numbers are not really random, given the same starting conditions (the seed) and the same sequence of operations, the same sequence of numbers will be generated. This is why it would not be a good iea to use the basic Random class as part of any cryptograhic or security related code since it may be possible for an attacker to figure out which sequnce is being generated and predict future numbers.
For a random number generator that emits non-deterministic values, take a look at SecureRandom.
See Random number generation, Computational methods on wikipedia for more info.
This means that when you create the Random object (e.g. at the start of your program), you will probably want to start with a new seed. Mostly people choose some time related value, such as the number of ticks.
The fact that the number sequences are the same given the same seed is actually very convenient if you want to debug your program: make sure you log the seed value and if something is wrong you can restart the program in the debugger using that same seed value. This means you can replay the scenario exactly. This would be impossible if you would (could) use a true random number generator.
With the same seed value, separate instances of Random will return/generate the same sequence of random numbers; more on this here:
http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter04/javaRandNums.html
Ruby Example:
class LCG; def initialize(seed=Time.now.to_i, a=2416, b=374441, m=1771075); #x, #a, #b, #m = seed % m, a, b, m; end; def next(); #x = (#a * #x + #b) % #m; end; end
irb(main):004:0> time = Time.now.to_i
=> 1282908389
irb(main):005:0> r = LCG.new(time)
=> #<LCG:0x0000010094f578 #x=650089, #a=2416, #b=374441, #m=1771075>
irb(main):006:0> r.next
=> 45940
irb(main):007:0> r.next
=> 1558831
irb(main):008:0> r.next
=> 1204687
irb(main):009:0> f = LCG.new(time)
=> #<LCG:0x0000010084cb28 #x=650089, #a=2416, #b=374441, #m=1771075>
irb(main):010:0> f.next
=> 45940
irb(main):011:0> f.next
=> 1558831
irb(main):012:0> f.next
=> 1204687
Based on the values a/b/m, the result will be the same for a given seed. This can be used to generate the same "random" number in two places and both sides can depend on getting the same result. This can be useful for encryption; although obviously, this algorithm isn't cryptographically secure.

Categories