How to generate random number java

How to generate random number java

How to generate random number java

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

Constructor Summary

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and TypeMethod and Description
DoubleStreamdoubles ()
DoubleStreamdoubles (double randomNumberOrigin, double randomNumberBound)DoubleStreamdoubles (long streamSize, double randomNumberOrigin, double randomNumberBound)IntStreamints (long streamSize, int randomNumberOrigin, int randomNumberBound)LongStreamlongs (long streamSize, long randomNumberOrigin, long randomNumberBound)

Methods inherited from class java.lang.Object

Constructor Detail

Random

Random

The invocation new Random(seed) is equivalent to:

Method Detail

setSeed

The implementation of setSeed by class Random happens to use only 48 bits of the given seed. In general, however, an overriding method may use all 64 bits of the long argument as a seed value.

nextBytes

The method nextBytes is implemented by class Random as if by:

nextInt

The method nextInt is implemented by class Random as if by:

nextInt

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity.

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.

The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order bits from the underlying pseudo-random number generator. In the absence of special treatment, the correct number of low-order bits would be returned. Linear congruential pseudo-random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low-order bits. Thus, this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two.

nextLong

The method nextLong is implemented by class Random as if by: Because class Random uses a seed with only 48 bits, this algorithm will not return all possible long values.

nextBoolean

The method nextBoolean is implemented by class Random as if by:

nextFloat

The method nextFloat is implemented by class Random as if by:

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as: This might seem to be equivalent, if not better, but in fact it introduced a slight nonuniformity because of the bias in the rounding of floating-point numbers: it was slightly more likely that the low-order bit of the significand would be 0 than that it would be 1.]

nextDouble

The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.

The method nextDouble is implemented by class Random as if by:

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as: This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity because of the bias in the rounding of floating-point numbers: it was three times as likely that the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity probably doesn’t matter much in practice, but we strive for perfection.]

nextGaussian

A pseudorandom int value is generated as if it’s the result of calling the following method with the origin and bound:

A pseudorandom int value is generated as if it’s the result of calling the following method with the origin and bound:

longs

longs

longs

A pseudorandom long value is generated as if it’s the result of calling the following method with the origin and bound:

longs

A pseudorandom long value is generated as if it’s the result of calling the following method with the origin and bound:

doubles

doubles

doubles

A pseudorandom double value is generated as if it’s the result of calling the following method with the origin and bound:

doubles

A pseudorandom double value is generated as if it’s the result of calling the following method with the origin and bound:

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2022, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Результат работы приведенного выше кода:

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

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

Результат работы предыдущего примера:

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

Заключение

Класс java.util.Random реализует линейный конгруэнтный генератор (LCG). Он отличается быстротой работы. Но при этом он не подходит для использования в режиме реального времени. Например, для генерации уникального идентификатора сессии на сервере, в научных экспериментах, криптографии лотереях и розыгрышах.

Дайте знать, что вы думаете по этой теме в комментариях. Мы очень благодарим вас за ваши комментарии, отклики, дизлайки, лайки, подписки!

Вадим Дворников автор-переводчик статьи « Random Number Generation in Java »

How to generate random numbers in Java

Generating random numbers in Java is a common requirement while working on Java application. In this article, we will look at how to generate random numbers in Java.

How to Generate Random Numbers in Java

1. Generate Random Number Using ThreadLocalRandom

If you are using Java 1.7 or later, ThreadLocalRandom should be your standard way to generate the random numbers in Java. There can be 2 variations while generating a random numbers in Java or any other language.

The nextDouble() and nextFloat() method allows generating the float and double values.It works similar to the above example and we can pass the lower and upper bound while generating the random double or float numbers.

2. Using Random Class

If you are not using Java 1.7 or higher, we can use the java.util.Random class to generate random numbers in Java.Here are some details for this class:

3. Using Math.random

We can use Math.random in case we only need integer or float random values.Here is a sample code from Math.random class:

4. Math.random() versus Random.nextInt(int)

If you are only interested in getting the int as the random number, you should choose the Random.nextInt(n) as this option is more efficient and less biased.Here are some of the advantages of using Random.nextInt over Math.random()

5. Generate Random numbers using Java 8

How to generate random number java

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

Constructor Summary

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and TypeMethodDescription
DoubleStreamdoubles ()
DoubleStreamdoubles ​(double randomNumberOrigin, double randomNumberBound)
DoubleStreamdoubles ​(long streamSize, double randomNumberOrigin, double randomNumberBound)
IntStreamints ​(long streamSize, int randomNumberOrigin, int randomNumberBound)
LongStreamlongs ​(long streamSize, long randomNumberOrigin, long randomNumberBound)

Methods declared in class java.lang.Object

Constructor Detail

Random

Random

The invocation new Random(seed) is equivalent to:

Method Detail

setSeed

The implementation of setSeed by class Random happens to use only 48 bits of the given seed. In general, however, an overriding method may use all 64 bits of the long argument as a seed value.

nextBytes

The method nextBytes is implemented by class Random as if by:

nextInt

The method nextInt is implemented by class Random as if by:

nextInt

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity.

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.

The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order bits from the underlying pseudo-random number generator. In the absence of special treatment, the correct number of low-order bits would be returned. Linear congruential pseudo-random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low-order bits. Thus, this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two.

nextLong

The method nextLong is implemented by class Random as if by: Because class Random uses a seed with only 48 bits, this algorithm will not return all possible long values.

nextBoolean

The method nextBoolean is implemented by class Random as if by:

nextFloat

The method nextFloat is implemented by class Random as if by:

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as: This might seem to be equivalent, if not better, but in fact it introduced a slight nonuniformity because of the bias in the rounding of floating-point numbers: it was slightly more likely that the low-order bit of the significand would be 0 than that it would be 1.]

nextDouble

The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.

The method nextDouble is implemented by class Random as if by:

The hedge «approximately» is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as: This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity because of the bias in the rounding of floating-point numbers: it was three times as likely that the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity probably doesn’t matter much in practice, but we strive for perfection.]

nextGaussian

A pseudorandom int value is generated as if it’s the result of calling the following method with the origin and bound:

A pseudorandom int value is generated as if it’s the result of calling the following method with the origin and bound:

longs

longs

longs

A pseudorandom long value is generated as if it’s the result of calling the following method with the origin and bound:

longs

A pseudorandom long value is generated as if it’s the result of calling the following method with the origin and bound:

doubles

doubles

doubles

A pseudorandom double value is generated as if it’s the result of calling the following method with the origin and bound:

doubles

A pseudorandom double value is generated as if it’s the result of calling the following method with the origin and bound:

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

How to generate random numbers in Java

Remember that the generated numbers are actually pseudorandom numbers, or “fake” random numbers. The generated numbers are parts of a very large sequence so they appear to be random, but they are not true random numbers. However, you can use it for cases in which true randomness and security are not required.

1. Generate random numbers using Math.random()

2. Generate random numbers using java.util.Random class

You can create a new instance of the Random class by using its empty constructor:

A random number generator produces pseudorandom numbers in a determinable sequence or pattern, and the seed value specifies the starting point in the sequence, so two Random instances constructed with the same seed will produce the same sequence of pseudorandom numbers.

Therefore, you can use the empty constructor in most cases. Use the seed parameter constructor when debugging the code with the same sequence of pseudorandom numbers.

The nextBoolean() method returns the next random boolean value, for example:

The nextBytes(byte[] bytes) method generates random bytes and put them into the specified byte array, for example:

The nextDouble() method returns the next random double value between 0.0 and 1.0. This method is used by the Math.random() method. For example, the code to generate 10 random numbers between 1 and 10 using Random class can be written as follows:

The nextFloat() method returns the next random float value between 0.0 and 1.

The nextInt() method returns the next random integer value with 2^32 possible int values.

The nextInt(int bound) method returns the next random integer value in the range from 0 (inclusive) to the specified bound value (exclusive). So the code to generate 10 random numbers between 1 and 100 can be written using nextInt() method as follows:

And the nextLong() method returns the next random long value.

3. Using Java Stream API for random numbers

This returns a stream of random int values. The number of values is unlimited.

The ints(long streamSize, int randomNumberOrigin, int randomNumberBound) method returns a limited stream of random int values between randomNumberOrigin (inclusive) and randomNumberBound (exclusive). For example, the code to print 10 random integer numbers between 1 and 10 can be written as compactly as:

The Random class also provides similar methods for producing a stream of random long values.

Now, you can see there are at least 3 different ways to generate random numbers between 1 and 100 in Java.

Using Math.random() method:

Using nextInt() method of Random class:

And using ints() method of Random class:

References:

Other Java Coding Tutorials:

About the Author:

How to generate random number java. Смотреть фото How to generate random number java. Смотреть картинку How to generate random number java. Картинка про How to generate random number java. Фото How to generate random number javaNam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источники информации:

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

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