Перейти к содержимому

Random java как работает

  • автор:

# Random Number Generation

Java provides, as part of the utils package, a basic pseudo-random number generator, appropriately named Random . This object can be used to generate a pseudo-random value as any of the built-in numerical datatypes ( int , float , etc). You can also use it to generate a random Boolean value, or a random array of bytes. An example usage is as follows:

NOTE: This class only produces fairly low-quality pseudo-random numbers, and should never be used to generate random numbers for cryptographic operations or other situations where higher-quality randomness is critical (For that, you would want to use the SecureRandom class, as noted below). An explanation for the distinction between "secure" and "insecure" randomness is beyond the scope of this example.

# Pseudo Random Numbers in Specific Range

The method nextInt(int bound) of Random accepts an upper exclusive boundary, i.e. a number that the returned random value must be less than. However, only the nextInt method accepts a bound; nextLong , nextDouble etc. do not.

Starting in Java 1.7, you may also use ThreadLocalRandom (source

(opens new window) ). This class provides a thread-safe PRNG (pseudo-random number generator). Note that the nextInt method of this class accepts both an upper and lower bound.

(opens new window) states that nextInt(int bound) can do weird things when bound is near 2 30 +1 (emphasis added):

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.

In other words, specifying a bound will (slightly) decrease the performance of the nextInt method, and this performance decrease will become more pronounced as the bound approaches half the max int value.

# Generating cryptographically secure pseudorandom numbers

Random and ThreadLocalRandom are good enough for everyday use, but they have a big problem: They are based on a linear congruential generator

(opens new window) , an algorithm whose output can be predicted rather easily. Thus, these two classes are not suitable for cryptographic uses (such as key generation).

One can use java.security.SecureRandom in situations where a PRNG with an output that is very hard to predict is required. Predicting the random numbers created by instances of this class is hard enough to label the class as cryptographically secure.

Besides being cryptographically secure, SecureRandom has a gigantic period of 2 160 , compared to Random s period of 2 48 . It has one drawback of being considerably slower than Random and other linear PRNGs such as Mersenne Twister

Note that SecureRandom implementation is both platform and provider dependent. The default SecureRandom (given by SUN provider in sun.security.provider.SecureRandom ):

  • on Unix-like systems, seeded with data from /dev/random and/or /dev/urandom .
  • on Windows, seeded with calls to CryptGenRandom() in CryptoAPI

# Generating Random Numbers with a Specified Seed

Using the same seed to generate random numbers will return the same numbers every time, so setting a different seed for every Random instance is a good idea if you don’t want to end up with duplicate numbers.

A good method to get a Long that is different for every call is System.currentTimeMillis()

# Select random numbers without duplicates

The method works by looping though an array that has the size of the requested length and finds the remaining length of possible numbers. It sets a random number of those possible numbers newRandSpot and finds that number within the non taken number left. It does this by looping through the range and checking to see if that number has already been taken.

For example if the range is 5 and the length is 3 and we have already chosen the number 2. Then we have 4 remaining numbers so we get a random number between 1 and 4 and we loop through the range(5) skipping over any numbers that we have already used(2).

Now let’s say the next number chosen between 1 & 4 is 3. On the first loop we get 1 which has not yet been taken so we can remove 1 from 3 making it 2. Now on the second loop we get 2 which has been taken so we do nothing. We follow this pattern until we get to 4 where once we remove 1 it becomes 0 so we set the new randomNumber to 4.

# Generating Random number using apache-common lang3

We can use org.apache.commons.lang3.RandomUtils to generate random numbers using a single line.

The method nextInt(int startInclusive, int endExclusive) takes a range.

Apart from int, we can generate random long , double , float and bytes using this class.

RandomUtils class contains the following methods-

# Remarks

Nothing is really random and thus the javadoc calls those numbers pseudorandom. Those numbers are created with a pseudorandom number generator

Генерируем случайное число Java

При разработке приложений часто нужно генерировать случайные числа. Java предоставляет для этого классы java.lang.Math и java.util.Random . В этой статье я расскажу о нескольких способах генерации случайных чисел и приведу конкретные примеры реализации.

Генерация случайных чисел с помощью класса Math

Чтобы сгенерировать случайное число Java предоставляет класс Math, доступный в пакете java.util. Этот класс содержит статичный метод Math.random(), предназначенный для генерации случайных чисел типа double .

Метод random( ) возвращает положительное число большее или равное 0,0 и меньшее 1,0. При вызове данного метода создается объект генератора псевдослучайных чисел java.util.Random.

Math.random() можно использовать с параметрами и без. В параметрах задается диапазон чисел, в пределах которого будут генерироваться случайные значения.

Пример использования Math.random():

Метод getRandomNumber( ) использует Math.random() для возврата положительного числа, которое больше или равно 0,0 или меньше 1,0 .

Результат выполнения кода:

Случайные числа в заданном диапазоне

Для генерации случайных чисел в заданном диапазоне необходимо указать диапазон. Синтаксис:

Разобьем это выражение на части:

  1. Сначала умножаем диапазон значений на результат, который генерирует метод random().Math.random() * (max — min)возвращает значение в диапазоне [0 , max- min], где max не входит в заданные рамки. Например, выражение Math.random()*5 вернет значение в диапазоне [0 , 5], в который 5 не входит.
  2. Расширяем охват до нужного диапазона. Это делается с помощью минимального значения.

Но выражение по-прежнему не охватывает максимальное значение.

  • Чтобы получить максимальное значение, прибавьте 1 к параметру диапазона (max — min). Это вернет случайное число в указанном диапазоне.

Существуют различные способы реализации приведенного выше выражения. Рассмотрим некоторые из них.

Случайное двойное число в заданном диапазоне

По умолчанию метод Math.random() при каждом вызове возвращает случайное число типа double . Например:

Вы можете вызвать предыдущий метод из метода main, передав аргументы, подобные этому.

Случайное целое число в заданном диапазоне

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

Метод getRandomIntegerBetweenRange() создает случайное целое число в указанном диапазоне. Так как Math.random() генерирует случайные числа с плавающей запятой, то нужно привести полученное значение к типу int. Этот метод можно вызвать из метода main, передав ему аргументы следующим образом:

Примечание . В аргументах также можно передать диапазон отрицательных значений, чтобы сгенерировать случайное отрицательное число в этом диапазоне.

Генерация случайных чисел с помощью класса Random

Класс java.util.Random можно применять для генерации случайных чисел различных типов: int, float, double, long и boolean .

Для этого сначала создайте экземпляр класса Random, а затем вызовите один из методов генератора случайных значений: nextInt( ), nextDouble( ) или nextLong( ).

Метод nextInt( ) класса Random принимает граничное целое число и возвращает случайное значение int от 0 (включительно) до указанного предела (не включая).

Пример использования метода nextInt( ):

Пример использования метода nextInt ( ) для генерации целого числа в заданном диапазоне:

Методы nextFloat ( ) и nextDouble( ) позволяют генерировать числа с плавающей запятой, а также значения типа double в диапазоне от 0,0 до 1,0.

Код для использования обоих методов:

Генерируем случайное число в Java 8 — особенности

В Java 8 был представлен новый метод класса java.util.Random — ints(). Он возвращает неограниченный поток псевдослучайных значений int. Данный метод позволяет указать диапазон чисел, задав минимальное и максимальное значения.

Пример использования метода Random.ints() для генерации случайных целочисленных значений в указанном диапазоне:

Метод getRandomNumberInts( ) генерирует поток случайных целых чисел от min(включительно) и до max (не входит в диапазон).

Метод ints( ) создает IntStream, поэтому будет вызвана функция findFirst( ). Она возвращает объект OptionalInt , который описывает первый элемент этого потока. Затем код вызывает метод getAsInt( ), чтобы вернуть значение int в OptionalInt.

Пример использования метода Random.ints() для генерации потока случайных целочисленных значений:

Код для вызова предыдущего метода:

Пример использования метода Random.ints() для генерации потока из диапазона случайных целочисленных значений:

Код для вызова приведенного выше метода:

Кроме ints( ) существует еще несколько методов, которые были добавлены к классу Random в Java 8. Они могут возвращать последовательный поток случайных чисел. Это:

Генерация случайных чисел

Класс Math библиотеки Java имеет метод random(), который генерирует случайное значение в диапазоне [0,1). Обратите внимание, что данный диапазон не включает 1 и при описании закрывается круглой скобкой. Можно ли предсказать сгенерированное значение? Теоретически возможно, но практически – это очень труднореализуемая задача. А поскольку существует небольшая вероятность предсказывания случайно-сгенерируемого значения, то такие числа принято называть не случайными, а псевдослучайными.

Чтобы получить псевдо-случайное число в определенном диапазоне необходимо значение метода random() умножить на величину диапазона значений. Например, необходимо генерировать значение в диапазоне от min до max. В этом случае можно использовать следующий код :

Допустим, что необходимо получить значение в диапазоне [1,10), где min=1, max=10 (10 исключительно)

Алгоритм работает следующим образом : диапазон [0;1) умножается на 9=(10-1), соответственно получаем :

  • нижняя граница: 0*9 = 0;
  • верхняя граница: 1*9 = 9,

получаем диапазон [0,9), к которому добавляем min=1. В результате имеем :

  • нижняя граница: 0 + 1 = 1;
  • верхняя граница: 9 + 1 = 10.

После подстановки значений в выражение, получим :

Диапазон [-10, 10)

Чтобы получить псевдослучайное число в диапазоне от -10 до 10 (исключительно), необходимо значение Math.random() умножить на 20 и вычесть 10, как это представлено в следующем примере :

Генерирование целочисленных псевдослучайных значений

Для генерирования целочисленных псевдослучайных значений используется представленное выше выражение, в котором произведение «приводится» к целочисленному значению. Например, попробуем получить псевдослучайное значение в диапазоне [5,20]. Обратите внимание, что закрывающаяся скобка квадратная, т.е. 20 входит в диапазон. В этом случае к разности между максимальным и минимальным значениями следует добавить 1, т.е. определить диапазон целочисленных значений [5,21), где 21 не попадает в желаемый диапазон :

Класс Random

В качестве генератора псевдослучайных чисел можно также использовать класс java.util.Random, имеющий два конструктора :

Поскольку Random создаёт псевдослучайное число, то определив начальное число, устанавливается начальная точка случайной последовательности, способствующая получению одинаковых случайных последовательностей. Чтобы избежать такого совпадения, обычно применяют второй конструктор с использованием в качестве инициирующего значения текущего времени. В таблице представлены наиболее часто используемые методы генератора Random :

Метод Описание
boolean nextBoolean() получение следующего случайного значения типа boolean
double nextDouble() получение следующего случайного значения типа double
float nextFloat() получение следующего случайного значения типа float
int nextInt() получение следующего случайного значения типа int
int nextInt(int n) получение следующего случайного значения типа int в диапазоне от 0 до n
long nextLong() получение следующего случайного значения типа long
void nextBytes(byte[] buf) формирование массива из случайно генерируемых значений

Пример получения псевдослучайного целочисленного значения с использованием класса Random :

С классом Random алгоритм получения псевдослучайного числа такой же, как и у метода random класса Math. Допустим, что нам необходимо получить случайное число в диапазоне [5,100], 100 включительно. В этом случае код может выглядеть следующим образом :

Класс SecureRandom

Для криптографии следует применять класс SecureRandom, использующий криптографически сильный генератор случайных чисел (random number generator RNG).

В следующем примере формируется массив псевдослучайных значений типа byte :

Этот же массив можно сформировать методом generateSeed :

Пример использования SecureRandom представлен на странице Симметричного шифрования.

A Guide to Math.random() in Java

A Guide to Math.random() in Java

The Math.random() method in Java is a built-in function which is a part of the java.Math class. One of the main benefits of the Math.random() method is its ease of use. It can be used to quickly generate random numbers within a specified range, making it a popular choice.

Another advantage of Math.random() is its performance. It is optimized to generate random numbers quickly, making it an ideal choice for high-performance applications where speed is a concern.

In this blog, we will discuss the basics of the Math.random() method and how to use it in Java to generate random numbers.

Table of Contents

What are random numbers?

Random numbers are numbers that use a large set of numbers and select a single number from them using a mathematical algorithm. It satisfies the following two conditions:

  1. The generated values are uniformly distributed over a definite interval.
  2. It is impossible to guess the future value based on current and past values.

Java Math.random() Method

The Math.random() method in Java is a static method in the java.lang.Math class that returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).

The Math.random() method generates a pseudo-random number using a deterministic algorithm, meaning that the sequence of numbers generated will be the same if the same seed is used. However, the default seed is based on the current time, which makes the generated numbers appear random.

The returned value of Math.random() can be used in a variety of ways, such as generating random numbers within a specific range, shuffling arrays, and more.

Method Signature

public static double random( )

Syntax

Return values

It returns a pseudorandom double value greater than or equal to 0.0 and less than 1.0

Parameters

There are no parameters to the Math.random() function

Java Math.random() Example

To understand Math.random() better, let’s look at some examples,

Example 1:

This code is an example of a simple Java program that uses the Math.random() method to generate a random floating-point number and print it to the console.

The main method declares a double variable number and assigns it to the result of calling the Math.random() method. This method returns a random floating-point number between 0.0 and 1.0.

Finally, the code prints the value of the number variable to the console using the System.out.println method, which outputs a string to the console. The string «Random number: » is concatenated with the value of number to produce the final output.

When this code is run, it will generate a new random number each time and print it to the console.

Output:

Math.random() in Java

Math.random() in Java

Generate random number between two numbers using Math.random() in Java

However, the random number obtained in Example 1 is not very useful in its current form. In most cases, we would not want to have a decimal number.

In order to produce a whole number with the pseudorandom number generator, we can multiply the random number by another number and round it to the nearest whole number.

For instance, suppose we want to generate a random number between 10 and 20. We could do so using this code:

Example 2:

In the main method we have declared two integer variables upperBound and lowerBound with values 20 and 10 respectively.

Next, we have calculated the range of possible values between lowerBound and upperBound using the formula (upperBound — lowerBound) + 1 . This is because the Math.random() method returns a value between 0.0 (inclusive) and 1.0 (exclusive), so to generate a random number within the specified range, we need to multiply the result of Math.random() by the range and then add lowerBound .

The code then uses a for loop to generate 10 random numbers within the specified range. The loop runs 10 times, and on each iteration, a new random number is generated by calling Math.random() and multiplying the result by range , then adding lowerBound . The generated number is then cast to an integer using the (int) operator, since Math.random() returns a floating-point number, and we only want integers.

Output:

Java Math.random() Number Between two numbers

Example 3:

Suppose we are building an app that generates random numbers which will be used to distinguish a customer’s order at a cruise line. These numbers will be added to the end of a customer’s name.

For instance, the number we want to generate should be between 300 and 600. In order to generate this number and prepare the customer’s order reference, we could use this code

Output:

Java Math.random() Number Between two numbers

Java Math.random() Number Between two numbers

Application of random numbers

There are times when you need to generate a random number in programming. For example, say that you are operating a cruise line, as a booking reference, you may want to add a random number to a customer’s order.

The Math.random() method in Java has many applications in various fields and industries. Some of the most common use cases for Math.random() include:

i.) Gaming: The Math.random() method is often used to generate random numbers for game development, such as random events, dice rolls, or card shuffling.

ii.) Statistical Analysis: Random numbers generated by Math.random() can be used in statistical analysis, such as Monte Carlo simulations, to model and predict outcomes.

iii.) Cryptography: In cryptography, random numbers generated by Math.random() can be used as keys or seeds to encrypt or decrypt sensitive information.

iv.) Testing: Math.random() can be used to generate random test data for software development, allowing developers to test their applications in a variety of scenarios.

v.) Artificial Intelligence: Math.random() can also be used in artificial intelligence and machine learning applications, such as genetic algorithms and neural networks, to generate random inputs for training and testing.

Advantages of using Math.random() in Java

  1. Simplicity: Math.random() is a simple and easy to use method for generating random numbers.
  2. Flexibility: It can be used to generate random numbers of various types, such as integers or decimals, within a specified range.
  3. Widely used: It is widely used in various applications, such as gaming, simulation, and statistical analysis.

Disadvantages of using Math.random() in Java

  1. Predictability: The sequence of random numbers generated by Math.random() can be predictable if not used correctly.
  2. Limited range: Math.random() only generates random numbers between 0 and 1, and the range must be scaled to meet the needs of a specific application.
  3. Non-uniform distribution: Math.random() generates random numbers with a non-uniform distribution, which can affect the accuracy of certain applications.
  4. Seed dependence: The random numbers generated by Math.random() are dependent on the seed value, and if the same seed is used, the same sequence of random numbers will be generated.

Conclusion

Math.random() method in Java is a convenient and efficient way to generate random numbers within a specified range.

Whether you need to generate random numbers for statistical analysis, gaming applications, or simulation purposes, the Math.random() method is a great tool to have in your arsenal.

However, it is important to note that the results generated by Math.random() are not completely random and may have some patterns or biases. For applications that require truly random numbers, it is recommended to use a specialized library or a hardware random number generator.

Regardless of its limitations, Math.random() remains a widely used method for generating random numbers in Java and is a valuable tool for developers.

Monitor your Java application for errors & exceptions with Atatus

With Atatus Java performance monitoring , you can monitor the performance and availability of your Java application in real-time and receive alerts when issues arise. This allows you to quickly identify and troubleshoot problems, ensuring that your application is always running smoothly.

One of the key features of Atatus is its ability to monitor the performance of your Java application down to the individual request level. This allows you to see exactly how long each request is taking to process, as well as any errors or exceptions that may have occurred. You can also see a breakdown of the different components of your application, such as the web server, database, and external services, to see how they are affecting performance.

Java APM

Java APM

In addition to monitoring performance, Atatus also allows you to track the availability of your Java application. This means that you can see when your application is down or experiencing errors, and receive alerts when this occurs. You can also see how long your application has been running, as well as any uptime or downtime trends over time.

Atatus also offers a range of tools and integrations that can help you to get the most out of your monitoring. For example, you can integrate Atatus with popular tools like Slack, PagerDuty, and Datadog to receive alerts and notifications in your preferred channels. You can also use Atatus’s APIs and SDKs to customize your monitoring and build custom integrations with your own tools and systems.

Overall, Atatus is a powerful solution for monitoring and managing the performance and availability of your Java application. By using Atatus, you can ensure that your application is always running smoothly and that any issues are quickly identified and resolved.

If you are not yet a Atatus customer, you can sign up for a 14-day free trial .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *