JavaRush /Java Blog /Random EN /Generate a random number in a given range
L2CCCP
Level 9

Generate a random number in a given range

Published in the Random EN group
Hello on the other side of the screen. Any of us, sooner or later, encounters the need to generate a random number in a given range, be it a real number or an integer. Generating a random number in a given range - 1For what? In fact, this is not important, it could be a function for calculating the chance of triggering some event, getting a random multiplier, or any other. So, we figured out why this is needed, namely for anything :) In fact, there are a lot of methods for obtaining a pseudo-random number, but I will give an example with the class Math, namely the method random(); What do we have? Calling the method Math.random()returns a pseudo-random real number ( double) from the range [0;1), that is, from 0 to 1 excluding 1, which means the maximum number in the range is 0.99999999999... Okay, we got a pseudo-random number, but what if we need our own range? For example, do we need a pseudorandom number from the range [0;100)? We write the code:
public static void main(String... args)
{
	final double max = 100.; // Максимальное число для диапазона от 0 до max
	final double rnd = rnd(max);

	System.out.println("Псевдослучайное вещественное число: " + rnd);
}

/**
 * Метод получения псевдослучайного вещественного числа от 0 до max (исключая max);
 */
public static double rnd(final double max)
{
	return Math.random() * max;
}
It turned out not bad, but max(in our case) we still won’t get it. In order to get a random number in the range [0;100] we need to add max1 to ours and then convert it to an integer like intor long(depending on the ranges you will use). We write the code:
public static void main(String... args)
{
	final int max = 100; // Максимальное число для диапазона от 0 до max
	final int rnd = rnd(max);

	System.out.println("Псевдослучайное целое число: " + rnd);
}

/**
 * Метод получения псевдослучайного целого числа от 0 до max (включая max);
 */
public static int rnd(int max)
{
	return (int) (Math.random() * ++max);
}
Note: As you can see, the max variable was incremented by the prefix form. (If you don’t know what this is, I advise you to read my article ) Great, we got what we wanted, but if we need a range not from 0, but for example [10;75] We write the code:
public static void main(String... args)
{
	final int min = 10; // Минимальное число для диапазона
	final int max = 75; // Максимальное число для диапазона
	final int rnd = rnd(min, max);

	System.out.println("Псевдослучайное целое число: " + rnd);
}

/**
 * Метод получения псевдослучайного целого числа от min до max (включая max);
 */
public static int rnd(int min, int max)
{
	max -= min;
	return (int) (Math.random() * ++max) + min;
}
Parsing the code from the method rnd:

Минимальное число диапазона = 10;
Максимальное число диапазона = 75;
max -= min; // Отнимаем от максимального значения минимальное для получения множителя псевдослучайного вещественного числа.
The maximum number after calculation is 65. The pseudo-random real number (for example) is 0.18283417347179454 (Was obtained by calling Math.random()). The maximum number was incremented with a prefix form before multiplication. The maximum number is now 66. Multiply 0.18283417347179454 by 66. The result of the multiplication is 12.06705544913844. We convert the result of multiplying the maximum number by a pseudorandom real number to an integer type int. We add the minimum number to the transformed result which is equal to 12. We return the result: 22 As can be seen from the analysis, even if the pseudo-random real number is equal to zero, we will return our minimum as a result of adding our minimum number with the result of multiplication. I hope this was useful and informative for you. Good luck in mastering Java ;) A couple more of my articles: What is incrementing and decrementing The modulo division operator
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION