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

Generating 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 meets with the need to generate a random number in the range we set, whether it be a real number or an integer. Generating a random number in a given range - 1For what? It doesn't really matter, it could be a function to calculate the chance to trigger some event, get a random multiplier, or whatever. So, for what it is necessary to figure it out, 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 with the method random(); What do we have? The method call Math.random()returns a pseudo-random real number ( double) from the range[0;1), that is, from 0 to 1 excluding 1, which means that the maximum number in the range is 0.99999999999... Well, we got a pseudo-random number, but what if we need our own range? For example, we need a pseudo-random 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 1 to ours max, and then convert it to an integer of type 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 has been incremented with the prefix form. (If you don’t know what it 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 (It was obtained by calling Math.random()). The maximum number before multiplication has been incremented by the prefix form. The maximum number is now 66 Multiply 0.18283417347179454 by 66. The result of the multiplication is 12.06705544913844. Converting the result of multiplying the maximum number by a pseudo-random real number to an integer typeint. We add the minimum number to the converted result, which is 12. We return the result: 22 As you can see from the analysis, even if the pseudo-random real number is equal to zero, then we will return our minimum as a result of adding our minimum number to the result of multiplication. I hope this was useful and informative for you. Good luck in learning Java ;) A couple more of my articles: What is incrementing and decrementing Modulo division operator
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION