Android java util random

Класс Random

Класс java.util.Random представляет собой генератор псевдослучайных чисел.

Класс представлен двумя конструкторами

  • Random() — создаёт генератор чисел, использующий уникальное начальное число
  • Random(long seed) — позволяет указать начальное число вручную

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

  • boolean nextBoolean() — возвращает следующее случайное значение типа boolean
  • void nextBytes(byte[] buf) — заполняет массив случайно созданными значениями
  • double nextDouble() — возвращает следующее случайное значение типа double
  • float nextFloat() — возвращает следующее случайное значение типа float
  • synchronized double nextGaussian() — возвращает следующее случайное значение гауссова случайного числа, т.е. значения, центрированное по 0.0 со стандартным отклонением в 1.0 (кривая нормального распределения)
  • int nextInt(int n) — возвращает следующее случайное значение типа int в диапазоне от 0 до n
  • int nextInt() — возвращает следующее случайное значение типа int
  • long nextLong() — возвращает следующее случайное значение типа long
  • synchronized void setSeeD(long seed) — устанавливает начальное значение

Пример для вывода случайного числа.

Случайные числа часто используются в играх. Допустим, мы хотим вывести случайные числа от 1 до 6 при бросании игрального кубика. Попробуем.

При проверке вы заметите две нестыковки. Во-первых, иногда выпадает число 0, которого нет на кубике, а во-вторых никогда не выпадает число 6. Когда вы помещаете число в параметр метода, то это означает, что выпадают числа в диапазоне от 0 до указанного числа, которое в этот диапазон не входит. Если вы будете использовать число 7, то шестёрка станет выпадать, но по-прежнему будет выпадать число 0. Поэтому пример следует немного отредактировать.

Для генерации 10 чисел типа int используйте код:

Генерация в определённом интервале

Нужны случайные числа от 100 до 200? Пишем код.

Случайные цвета

Работать с числами не слишком интересно. Давайте поработаем со цветом. В Android некоторые цвета имеют конкретные названия, но по сути они являются числами типа int, например, красный цвет имеет константу Color.RED. Вам не надо знать, какое число соответствует этому цвету, так как проще понять по его названию.

Щёлкая по кнопке, вы будете менять её цвет случайным образом.

Лотерея «6 из 49»

Сформируем шесть случайных чисел из 49 и занесём их в списочный массив.

SecureRandom

Стандартный класс Random обычно используют для простых задач, не связанных с шифрованием. Для криптографии следует использовать схожий класс java.security.SecureRandom.

Не забывайте, что в классе Math есть метод random(), возвращающий случайное число от 0 до 1 (единица в диапазон не входит).

Источник

Генерируем случайное число 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. Они могут возвращать последовательный поток случайных чисел. Это:

  • LongStream longs( );
  • DoubleStream doubles( ).

Заключение

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

Пожалуйста, оставьте свои комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, отклики, дизлайки, лайки, подписки!

Пожалуйста, оставляйте ваши отзывы по текущей теме материала. За комментарии, отклики, лайки, дизлайки, подписки огромное вам спасибо!

Источник

Android java util random

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random . Java implementations must use all the algorithms shown here for the class Random , for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

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

Читайте также:  Strings xml file android

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

Constructors
Constructor and Description
Random ()

Method Summary

All Methods Instance Methods Concrete Methods
Modifier and Type Method and Description
DoubleStream doubles ()
DoubleStream doubles (double randomNumberOrigin, double randomNumberBound) DoubleStream doubles (long streamSize, double randomNumberOrigin, double randomNumberBound) IntStream ints (int randomNumberOrigin, int randomNumberBound) IntStream ints (long streamSize, int randomNumberOrigin, int randomNumberBound) LongStream longs (long randomNumberOrigin, long randomNumberBound) LongStream longs (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.

The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1 . The method next is implemented by class Random by atomically updating the seed to and returning This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.

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 general contract of nextFloat is that one float value, chosen (approximately) uniformly from the range 0.0f (inclusive) to 1.0f (exclusive), is pseudorandomly generated and returned. All 2 24 possible float values of the form m x 2 -24 , where m is a positive integer less than 2 24 , are produced with (approximately) equal probability.

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

The general contract of nextGaussian is that one double value, chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0 , is pseudorandomly generated and returned.

The method nextGaussian is implemented by class Random as if by a threadsafe version of the following: This uses the polar method of G. E. P. Box, M. E. Muller, and G. Marsaglia, as described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.4.1, subsection C, algorithm P. Note that it generates two independent values at the cost of only one call to StrictMath.log and one call to StrictMath.sqrt .

A pseudorandom int value is generated as if it’s the result of calling the method nextInt() .

A pseudorandom int value is generated as if it’s the result of calling the method nextInt() .

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

A pseudorandom long value is generated as if it’s the result of calling the method nextLong() .

longs

A pseudorandom long value is generated as if it’s the result of calling the method nextLong() .

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

A pseudorandom double value is generated as if it’s the result of calling the method nextDouble() .

doubles

A pseudorandom double value is generated as if it’s the result of calling the method nextDouble() .

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:

  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

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, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Читайте также:  The cheapest android smartphone
Оцените статью