Random number in java with range

Generate random numbers in range

Random number means a different number every time the application is executed. Sounds interesting but have you thought why is it required.
Random number generator becomes handy when you want to create a unique name. This article will explain below 3 different methods to generate a random number in java in range.

Java random number generator
Java provides many approaches to generate unique random numbers between a given range. These approaches are discussed below to create a random number generator program.
All the approaches assume that the random number generated is in the range 1 to 50. Method 1 : Using Math class
java.lang.Math class has a random() method which generates a decimal value of type double which is greater than 0.0 and less than 1.0(0.9999), that is in the range 0.0(inclusive) to 1.0(exclusive). This value is different every time the method is invoked. In order to generate a number between 1 to 50, we multiply the value returned by Math.random() method by 50.
This makes its range as 0.0 to 49.995. Now add 1 to it.
This increases its range as 1.0 to 50.995. If this result is cast to an int , the range will be 1 to 50.
Below program demonstrates this algorithm and shows the result for different executions.

public class RandomNumberGenerator < public static void main(String[] args) < usingMathClass(); >static void usingMathClass() < double randomDouble = Math.random(); randomDouble = randomDouble * 50 + 1; int randomInt = (int) randomDouble; System.out.println(randomInt); >>

Random number generated is : 50
Random number generated is : 27
Random number generated is : 32
Random number generated is : 21

Method 2 : Using Random class
java.util.Random class provides a method nextInt() which can generate random numbers between 0 and a specified upper boundary.
This method takes an integer as argument.
This integer value represents the upper limit of the random number that will be generated by this method.
The random number generated will be between 0(inclusive) and the upper boundary value(exclusive). In order to generate a random number between 1 and 50 we create an object of java.util.Random class and call its nextInt() method with 50 as argument.
This will generate a number between 0 and 49 and add 1 to the result which will make the range of the generated value as 1 to 50.

import java.util.Random; public class RandomNumberGenerator < public static void main(String[] args) < usingRandomClass(); >static void usingRandomClass() < Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(50) + 1; System.out.println("Random number is : " + randomInt); >>

Random number generated is : 2
Random number generated is : 29
Random number generated is : 8
Random number generated is : 16

Method 3 : Using ThreadLocalRandom

Java 7 has provided a new class called java.util.concurrent.ThreadLocalRandom . This class has methods to generate random numbers. This class is appropriate for generating random numbers in multithreaded environments since it will be a less overhead as compared to using java.util.Random class.
ThreadLocalRandom class has a method nextInt() which takes two arguments representing the lower and upper boundary values and returns an integer between those values. The result will be between lower boundary(inclusive) and upper boundary(exclusive). For generating a number between 1 and 50, the lower and upper bounds passed to this method will be 1 and 51 respectively. In order to call this method, first its current method is called, then nextInt() is called as ThreadLocalRandom.current().nextInt(1, 51); .
Program for generating random numbers using this approach is given below.

import java.util.concurrent.ThreadLocalRandom; public class RandomNumberGenerator < public static void main(String[] args) < usingThreadLocalClass(); >static void usingThreadLocalClass() < int randomInt = ThreadLocalRandom.current().nextInt(1, 51); System.out.println("Random number is : " + randomInt); >>

Random number generated is : 11
Random number generated is : 1
Random number generated is : 35
Random number generated is : 21

  1. Upper boundary provided to randomInt() method of java.util.Random class should be positive. If it is less than 0, the method throws a java.lang.IllegalArgumentException .
  2. java.lang.Math class uses java.util.Random class’ nextDouble() method for random number generation.
  3. java.util.concurrent.ThreadLocalRandom is a child class of java.util.Random .
  4. java.util.Random class provides methods to generate random numbers of different types such as long , float , boolean , double .
  5. For generating a random number between 0 and 1 use random() method of java.util.Math class(Method 1).
  6. nextInt() method of java.util.concurrent.ThreadLocalRandom with two consecutive numbers as lower and upper range will always produce lower range as result. That is, nextInt(50, 51) will always give 50 as result.
Читайте также:  Все основные команды python

Not willing to read? Watch the video

Hope you liked this post and learnt something from it.

Источник

Генерация случайного числа в заданном диапазоне

Java-университет

Генерация случайного числа в заданном диапазоне - 1

Привет по ту сторону экрана. Любой из нас рано или поздно встречается с необходимостью генерировать случайное число в заданном нами диапазоне будь то вещественное или целое число. Для чего? На самом деле это не важно, это может быть функция для расчета шанса для запуска какого нибудь события, получение случайного множителя или любого другая. Итак, для чего это нужно разобрались, а именно для чего угодно 🙂 На самом деле методов получения псевдослучайного числа очень много, я же приведу пример с классом Math , а именно с методом random() ; Что же мы имеем? Вызов метода Math.random() возвращает псевдослучайное вещественное число ( double ) из диапазона [0;1) , то есть, от 0 до 1 исключая 1, а значит максимальное число в диапазоне это 0.99999999999. Хорошо, мы получили псевдослучайное число, но если нам нужен свой диапазон? К примеру, нам нужно псевдослучайное число из диапазона [0;100)? Пишем код:

 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)

Получилось не плохо, но max (в нашем случае) мы все равно не получим. Для того чтобы получить случайное число в диапазоне [0;100] нам необходимо прибавить к нашему max 1, а затем преобразовать в целое число типа int или long (зависит от диапазонов которые Вы будете использовать). Пишем код:

 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)

Примечание: Как видите переменная max была инкрементирована префиксной формой. (Если Вы не знаете что это советую почитать мою статью) Отлично, мы получили то что хотели, но если нам нужен диапазон не от 0, а к примеру [10;75] Пишем код:

 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)
 Минимальное число диапазона = 10; Максимальное число диапазона = 75; max -= min; // Отнимаем от максимального значения минимальное для получения множителя псевдослучайного вещественного числа. 

Максимальное число после расчета равно 65 Псевдослучайное вещественное число (к примеру) равно 0.18283417347179454 (Был получен при вызове Math.random() ). Максимальное число перед умножением было инкрементировано префиксной формой. Максимальное число теперь 66 Умножаем 0.18283417347179454 на 66. Результат умножения равен 12.06705544913844. Преобразовываем результат умножения максимального числа на псевдослучайное вещественное число к типу целого числа int . Прибавляем минимальное число к преобразованному результату который равен 12. Возвращаем результат: 22 Как видно из разбора, даже если псевдослучайное вещественное число будет равно нулю, то мы вернем наш минимум в результате сложения нашего минимального числа с результатом умножения. Надеюсь для Вас это было полезно и познавательно. Успехов в освоении Java 😉 Еще пару моих статей: Что такое инкрементирование и декрементирование Оператор деления по модулю

Читайте также:  Перевести html в svg

Источник

Generate random numbers in range

Random number means a different number every time the application is executed. Sounds interesting but have you thought why is it required.
Random number generator becomes handy when you want to create a unique name. This article will explain below 3 different methods to generate a random number in java in range.

Java random number generator
Java provides many approaches to generate unique random numbers between a given range. These approaches are discussed below to create a random number generator program.
All the approaches assume that the random number generated is in the range 1 to 50. Method 1 : Using Math class
java.lang.Math class has a random() method which generates a decimal value of type double which is greater than 0.0 and less than 1.0(0.9999), that is in the range 0.0(inclusive) to 1.0(exclusive). This value is different every time the method is invoked. In order to generate a number between 1 to 50, we multiply the value returned by Math.random() method by 50.
This makes its range as 0.0 to 49.995. Now add 1 to it.
This increases its range as 1.0 to 50.995. If this result is cast to an int , the range will be 1 to 50.
Below program demonstrates this algorithm and shows the result for different executions.

public class RandomNumberGenerator < public static void main(String[] args) < usingMathClass(); >static void usingMathClass() < double randomDouble = Math.random(); randomDouble = randomDouble * 50 + 1; int randomInt = (int) randomDouble; System.out.println(randomInt); >>

Random number generated is : 50
Random number generated is : 27
Random number generated is : 32
Random number generated is : 21

Method 2 : Using Random class
java.util.Random class provides a method nextInt() which can generate random numbers between 0 and a specified upper boundary.
This method takes an integer as argument.
This integer value represents the upper limit of the random number that will be generated by this method.
The random number generated will be between 0(inclusive) and the upper boundary value(exclusive). In order to generate a random number between 1 and 50 we create an object of java.util.Random class and call its nextInt() method with 50 as argument.
This will generate a number between 0 and 49 and add 1 to the result which will make the range of the generated value as 1 to 50.

import java.util.Random; public class RandomNumberGenerator < public static void main(String[] args) < usingRandomClass(); >static void usingRandomClass() < Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(50) + 1; System.out.println("Random number is : " + randomInt); >>

Random number generated is : 2
Random number generated is : 29
Random number generated is : 8
Random number generated is : 16

Читайте также:  Python tkinter disable buttons

Method 3 : Using ThreadLocalRandom

Java 7 has provided a new class called java.util.concurrent.ThreadLocalRandom . This class has methods to generate random numbers. This class is appropriate for generating random numbers in multithreaded environments since it will be a less overhead as compared to using java.util.Random class.
ThreadLocalRandom class has a method nextInt() which takes two arguments representing the lower and upper boundary values and returns an integer between those values. The result will be between lower boundary(inclusive) and upper boundary(exclusive). For generating a number between 1 and 50, the lower and upper bounds passed to this method will be 1 and 51 respectively. In order to call this method, first its current method is called, then nextInt() is called as ThreadLocalRandom.current().nextInt(1, 51); .
Program for generating random numbers using this approach is given below.

import java.util.concurrent.ThreadLocalRandom; public class RandomNumberGenerator < public static void main(String[] args) < usingThreadLocalClass(); >static void usingThreadLocalClass() < int randomInt = ThreadLocalRandom.current().nextInt(1, 51); System.out.println("Random number is : " + randomInt); >>

Random number generated is : 11
Random number generated is : 1
Random number generated is : 35
Random number generated is : 21

  1. Upper boundary provided to randomInt() method of java.util.Random class should be positive. If it is less than 0, the method throws a java.lang.IllegalArgumentException .
  2. java.lang.Math class uses java.util.Random class’ nextDouble() method for random number generation.
  3. java.util.concurrent.ThreadLocalRandom is a child class of java.util.Random .
  4. java.util.Random class provides methods to generate random numbers of different types such as long , float , boolean , double .
  5. For generating a random number between 0 and 1 use random() method of java.util.Math class(Method 1).
  6. nextInt() method of java.util.concurrent.ThreadLocalRandom with two consecutive numbers as lower and upper range will always produce lower range as result. That is, nextInt(50, 51) will always give 50 as result.

Not willing to read? Watch the video

Hope you liked this post and learnt something from it.

Источник

Оцените статью