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

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.

Related

How Java random generator works?

I wrote program that simulates dice roll
Random r = new Random();
int result = r.nextInt(6);
System.out.println(result);
I want to know if there is a way to "predict" next generated number and how JVM determines what number to generate next?
Will my code output numbers close to real random at any JVM and OS?
They're pseudorandom numbers, meaning that for general intents and purposes, they're random enough. However they are deterministic and entirely dependent on the seed. The following code will print out the same 10 numbers twice.
Random rnd = new Random(1234);
for(int i = 0;i < 10; i++)
System.out.println(rnd.nextInt(100));
rnd = new Random(1234);
for(int i = 0;i < 10; i++)
System.out.println(rnd.nextInt(100));
If you can choose the seed, you can precalculate the numbers first, then reset the generator with the same seed and you'll know in advance what numbers come out.
I want to know if there is a way to "predict" next generated number and how JVM determines what number to generate next?
Absolutely. The Random class is implemented as a linear congruential number generator (LCNG). The general formula for a linear congruential generator is:
new_state = (old_state * C1 + C2) modulo N
The precise algorithm used by Random is specified in the javadocs. If you know the current state of the generator1, the next state is completely predictable.
Will my code output numbers close to real random at any JVM and OS?
If you use Random, then No. Not for any JVM on any OS.
The sequence produced by an LCNG is definitely not random, and has statistical properties that are significantly different from a true random sequence. (The sequence will be strongly auto-correlated, and this will show up if you plot the results of successive calls to Random.nextInt().)
Is this a problem? Well it depends on what your application needs. If you need "random" numbers that are hard to predict (e.g. for an algorithm that is security related), then clearly no. And if the numbers are going to be used for a Monte Carlo simulation, then the inate auto-correlation of a LCNG can distort the simulation. But if you are just building a solitaire card game ... it maybe doesn't matter.
1 - To be clear, the state of a Random object consists of the values of its instance variables; see the source code. You can examine them using a debugger. At a pinch you could access them and even update them using Java reflection, but I would not advise doing that. The "previous" state is not recorded.
Yes, it is possible to predict what number a random number generator will produce next. I've seen this called cracking, breaking, or attacking the RNG. Searching for any of those terms along with "random number generator" should turn up a lot of results.
Read How We Learned to Cheat at Online Poker: A Study in Software Security for an excellent first-hand account of how a random number generator can be attacked. To summarize, the authors figured out what RNG was being used based on a faulty shuffling algorithm employed by an online poker site. They then figured out the RNG seed by sampling hands that were dealt. Once they had the algorithm and the seed, they knew exactly how the deck would be arranged after later shuffles.
You can also refer this link.
Check How does java.util.Random work and how good is it?:
In other words, we begin with some start or "seed" number which
ideally is "genuinely unpredictable", and which in practice is
"unpredictable enough". For example, the number of milliseconds— or
even nanoseconds— since the computer was switched on is available on
most systems. Then, each time we want a random number, we multiply the
current seed by some fixed number, a, add another fixed number, c,
then take the result modulo another fixed number, m. The number a is
generally large. This method of random number generation goes back
pretty much to the dawn of computing1. Pretty much every "casual"
random number generator you can think of— from those of scientific
calculators to 1980s home computers to currentday C and Visual Basic
library functions— uses some variant of the above formula to generate
its random numbers.
And also Predicting the next Math.random() in Java

What is random seed about?

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

What's the importance of using Random.setSeed?

When writing Java program, we use setSeed in the Random class. Why would we use this method?
Can't we just use Random without using setSeed? What is the main purpose of using setSeed?
One use of this is that it enables you to reproduce the results of your program in future.
As an example, I wanted to compute a random variable for each row in a database. I wanted the program to be reproducible, but I wanted randomness between rows. To do this, I set the random number seed to the primary key of each row. That way, when I ran the program again, I got the same results, but between rows, the random variable was pseudo random.
The seed is used to initialize the random number generator. A seed is used to set the starting point for generating a series of random numbers. The seed sets the generator to a random starting point. A unique seed returns a unique random number sequence.
This might be of help .
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.
I can see two reasons for doing this:
You can create a reproducible random stream. For a given seed, the same results will be returned from consecutive calls to (the same) nextX methods.
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
You feel, for some reason, that your seed is of a higher quality than the default source (which I'm guessing is derived from the current time on your PC).
A specific seed will always give the same sequence of "pseudo-random" numbers. So there are only 2^48 different sequences in Random because setSeed only uses 48-bits of the seed parameter! Besides setSeed, one may also use a constructor with a seed (e.g. new Random(seed)).
When setSeed(seed) or new Random(seed) are not used, the Random() constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.
Java reference for the above information: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Random.html
In the ordinary case, don't use a seed. Just use the empty constructor Random() and don't call setSeed. This way you'll likely get different pseudo-random numbers each time the class is constructed and invoked.
For data dependent debugging, where you want to repeat the same pseudo-random numbers, use a specific seed. In this case, use Random(seed) or setSeed(seed).
For non-security critical uses, there's no need to worry whether the specific seed/sequence might be recognized and subsequent numbers predicted, because of the large range of seeds. However, "Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications." source
Several others have mentioned reproducibility. Reproducibility is at the heart of debugging, you need to be able to reproduce the circumstances in which the bug occurred.
Another important use of reproducibility is that you can play some statistical games to reduce the variability of some estimates. See Wikipedia's Variance Reduction article for more details, but the intuition is as follows. Suppose you're considering two different layouts for a bank or a grocery store. You can't build them both and see which works better, so you use simulation. You know from queueing theory that the size of lines and delays customers experience are partly due to the layout, but also partly due to the variation in arrival times, demand loads, etc, so you use randomness in your two models. If you run the models completely independently, and find that the lines are bigger in layout 1 than in layout 2, it might be because of the layout or it might be because layout 1 just happened to get more customers or a more demanding mix of transactions due to the luck of the draw. However, if both systems use the exact same set of customers arriving at the same times and having the same transaction demands, it's a "fairer" comparison. The differences you observe are more likely to be because of the layout. You can accomplish this by reproducing the randomness in both systems - use the same seeds, and synchronize so that the same random numbers are used for the same purpose in both systems.

How to generate random values across many requests

I want to generate some random numbers for many Servlet requests.
The problem is if i use a new Random object in each servlet, the overall probability will be incorrect.
E.g. with around 10000+ reqeusts, i expect all random value should be evenly distributed within the range.
So why not use a global Random instance?
Or you can use ThreadLocalRandom which is faster. And it is kind of global because you cannot really create an instance of it. You can get an instance by calling ThreadLocalRandom.current(). In Java 7, it returns a per-thread instance. In Java 8, it is further optimized, it'll always return the same singleton.
It is a little bit complicated to get really random sequence using Random. Random is LCG-based with 2^48 period and you need to be very careful with seed. There is a way to generate single sequence using DataStore to keep your current value, but performance will be not very good because you will need to update value every time you generate new random number. It means that you will be able too reach 10-20 request/sec without memcahce and probably around 100 req/sec with memcache. Sharding will not be very helpful because you need to keep atomic seed value.
Algorithm will looks like:
Generate first Integer (to use long you will need additional processing. It is much simpler to generate int).
set seed = random <<< 16
Save seed to DataStore (do not forget about transaction)
On every next request (whole op should be in a single transcation):
4.1. Read seed from DataStore
4.2. Create new Random with your seed.
4.3. Generate new int.
4.4. Set seed = random <<< 16
4.5. Save seed to DataStore

Are random Numbers really unPredictable in Java?

there is some ways to generate random Numbers in java
one of them is this:
Random rand=new Random();
int randomInteger=rand.nextInt();
now my question is this: can we predict next random Number?
edited after 4 answers:
my real problem is this:
I'm working on a Snake Game( nibbles in Linux) and I'm programing the snake to move, now I want to know if it's possible to Predict the next place that the apple will appear.
is it possible?
You can not only predict it, but know it absolutely, if you know exactly what System.currentTimeMillis would return when you called new Random(). That's because new Random() is a shortcut for new Random(System.currentTimeMillis()), which sets the seed of a pseudo-random generator. (Well, that's what it did when I last looked at the source; the docs don't actually say it has to use that.) if you know the seed that new Random() used. Pseudo-random generators are deterministic, if you know the seed, you know the sequence. Update: Looking at the Java 6 source [I don't have Java 7 source handy], the default seed is a combination of a seed number that gets incremented on use, plus System.nanoTime. So you'd need to know both of those. Raises the bar.
If you don't know the exact value of System.currentTimeMillis() as of when new Random() occurs the seed used by new Random(), then it's very difficult indeed to predict what the next value will be. That's the point of pseudo-random generators. I won't say it's impossible. Just really, really hard to do with any degree of confidence.
Update after question edit: It's possible, but very, very hard, and in terms of doing so in a way that would allow a player to improve their score in the game, I'd say you can ignore it.
The "random" numbers generated by the Random class are generated algorithmically, and as such are really pseudo-random numbers. So yes, in theory, you can predict the next number. Knowing one number that Random has produced, though, or even a series of numbers, isn't enough information to predict the next number; you would also need to know the seed that the Random object is using, and you would need to follow its pseudo-random number generation algorithm.
If you would like a repeatable set of "random" numbers, you can specify your own seed when creating an instance of Random, e.g.
Random rand = new Random(1234); // Replace 1234 with any value you'd like
Every time you instantiate Random with the same seed, you'll get the same series of numbers. So, for example, you could write a small command-line program that instantiates Random with some seed and prints a list of the numbers it returns, and then instantiate Random with the same seed in your code. Then you would know which numbers your code will receive and in what order. That's very handy for debugging.
There could be NO really random numbers on deterministic devices like computer. But.
If you want a cryptographically secure random number, use SecureRandom: http://docs.oracle.com/javase/6/docs/api/java/security/SecureRandom.html
Random uses a deterministic algorithm:
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.
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#Random
Essentially, if you know the seed of the random number generator, you can predict the entire sequence with certainty. If you don't, no matter how many numbers you generate, there's no way to accurately predict the next one.
Note that if you're relying on the numbers being unpredictable for security, you should be using java.secure.SecureRandom rather than java.util.Random.
As others answer this question, it is possible to predict randomness of java.util.Random if you know the starting seed.
If you are working on a linux like system, take a look at these special files /dev/random and dev/urandom. Reads from these files are said to return "better" random numbers, the randomness depends on keyboard activity, mouse movement and some other exotic factors.
See this Wikipedia page for details. This page also says equivalent APIs exist in Windows.

Categories