Pseudorandom numbers generation in Java
In this tutorial, we will learn how to generate pseudorandom numbers in Java. There are many situations where we need some random numbers to be generated. As a result, we use Pseudorandom algorithms.
Generation of pseudorandom numbers in Java
What are random numbers?
Definition: Numbers that occur in a sequence.
Conditions:
- The values are uniformly distributed.
- Future values cannot be predicted from current or past values.
PSEUDORANDOM NUMBER GENERATOR (PRNG)
PSEUDORANDOM NUMBER GENERATOR(PRNG) uses some mathematical formulas to generate random numbers. These are not random numbers but are in fact deterministic, hence the name pseudo-random.
WAYS TO GENERATE THESE NUMBERS
- Math.random()
- util.Random.nextInt()
- setSeed(long seed)
Let us understand these one by one
1: Math.random() method
Math.random() method is a static method.
SYNTAX: public static double random()
Math.random() method is present in java.lang package [java.lang.Math.random()].
It returns a pseudorandom value of datatype-double.
This method is used to generate a value between 0.0 and 1.0.
So let us understand this method by a simple example.
package randomnumbersgeneration; public class RandomNumbersGeneration { public static void main(String[] args) { double random_num=Math.random(); System.out.println("Random number:"+random_num); } }
Output:
Random number:0.5689894292803638
The above code snippet explains the use of Math.random() method.
2: util.Random.nextInt()
Random.nextInt() is present in java.util.Random package.
java.util.Random().nextInt() is used to generate pseudorandom integer values and these values are uniformly distributed.
As a result, all 2³² possible integer values can be generated with equal probability.
Example:
So let us understand this by a simple example.
package randomnumbersgeneration; import java.util.Random; class RandomNumbersGeneration { public static void main(String[] args) { Random rn = new Random(); System.out.println(rn.nextInt()); } }
Output:
380679889
3: setSeed(long seed)
setSeed(long seed) sets the seed of this random number generator using a single long seed. ‘Seed‘ is a starting point from which something grows, and in our case, it is the sequence of numbers. You can provide constant seed value to generate the same sequence every time. However, you can change the value of the seed each time you run the program if you want your output to be unpredictable.
So let us understand this by a simple example.
package randomnumbersgeneration; import java.util.Random; class RandomNumbersGeneration { public static void main(String[] args) { Random rnum = new Random(); rnum.setSeed(20); System.out.println("Object after seed: " + rnum.nextInt()); } }
Output:
Object after seed: -1150867590
In the above code snippet, we use a method called setseed() to generate a pseudorandom number.
Also read:
Leave a Reply