Interview Kickstart has enabled over 21000 engineers to uplevel.
The math.random() method in Java helps generate pseudorandom numbers, which is very useful while stress-testing solutions against randomly generated values. Often in interviews, we see candidates need to check for corner cases and validate them. Instead of hardcoding values, it’s better to stress test against randomly generated values. Hence this article is dedicated to the math.random() method.
In this article, we’ll discuss:
Math.random() is an in-build method from the java.lang.Math package. It’s useful in returning a pseudorandom double greater than or equal to 0.0 and less than 1.0. These numbers are generated pseudorandomly with (approximately) uniform distribution over the below range:
0.0<=value<1.0, where value is the random number
It first creates an object of the java.util.Random class and then calls the nextDouble() method inside it to return a double.
So the first time we call the Math.random method, it will internally create a single new pseudorandom-number generator using the java.util.Random class. We use this new pseudorandom-number generator for all calls to this method and nowhere else.
Also, this method is appropriately synchronized to allow correct usage by more than one thread. That said, if many threads need to generate pseudorandom numbers at a great rate, that may reduce the contention for each thread to have its own pseudo-random-number generator.
Here’s the declaration for java.lang.Math.random() method:
public static double random()
Let’s jump into some code and then try to understand the functionalities of Math.random.
public class Main {
public static void main(String[] args) {
double value = Math.random();
System.out.println("Random Value generated = "+value);
}
}
Output :
Random Value generated = 0.7201678640927276
In the above program, we use Math.random() to generate a random double and store it in a variable named value. Every time we execute this program, a new random double is printed in the console. The reason is Math.random returns a random double within the range 0.0 (inclusive) and 1.0 (exclusive).
By far now, we have understood the functionality of Math.random. So let's look at some of the use-cases of it.
Let’s say we have a range [ left, right ] inclusive. We can use the random() method to generate random numbers between this range. Let's see how.
public class Main {
public static void main(String[] args) {
int left = 100;
int right = 200;
int randomInteger = getRandomInteger(left , right);
System.out.println("Random Integer in [left,right] = "+randomInteger);
}
private static int getRandomInteger(int left, int right) {
int range = right - left + 1;
return (int)(Math.random() * range) + left;
}
}
Output :
Random Integer in [left,right] = 118
Math.random() returns a double, so we cast it to an integer value.
Here, getRandomInteger method returns an integer within a user-defined range. For our case, the values of left and right equal 100 and 200, respectively. The method returns a random integer in the range [100, 200] inclusive.
We can re-use the functionality of the random() method that allows us to return a value in a range. So we can keep the range as [ 0, 25 ] inclusive since we have 26 characters and then call the method getRandomCharacter( left, right ) to return a random char every time.
public class Main {
public static void main(String[] args) {
int left = 0;
int right = 25;
char randomCharacter = getRandomCharacter(left , right);
System.out.println("Random char in ['a','z'] = "+randomCharacter);
}
private static char getRandomCharacter(int left, int right) {
int range = right - left + 1;
return (char) (((int)( Math.random() * range) + left)+'a');
}
}
Output :
Random char in ['a','z'] = i
Now we know ways to generate both random Integers and Characters.
Parameter bound is the upper bound (exclusive) and Must be positive.
Math.random(): This method uses Random.nextDouble() internally. Random.nextDouble() uses the Random.next() method twice to generate a double that has approximately uniformly distributed bits in its mantissa. Thus it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(bound) uses Random.next() less than twice on average. It uses Random.next() once, and if the value obtained is above the highest multiple of bound and below Integer MAX_VALUE, the method tries again. Otherwise, it returns the value modulo bound, which prevents the values above the highest multiple of bound below Integer.MAX_VALUE skewing the distribution. Thus, it returns a value that is (approximately) uniformly distributed in the range 0 to bound -1.
Question 1: What is the return type of the Math.random() method?
It returns a double in the range 0.0 ( inclusive ) and 1.0 (exclusive)
Question 2: Do Math.random and Random.nextInt() belong to the same java packages?
No. Math.random belongs to java.lang.Math, whereas Random class is present in java.util package
Question 3: To generate random integers, which is better Math.random() or Random.nextInt()?
Random.nextInt() is better in terms of performance.
Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!
If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
————
Article contributed by Problem Setters Official
Attend our webinar on
"How to nail your next tech interview" and learn