Как использовать рандом в java

Как использовать рандом в 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

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, 2021, 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.

Источник

Как использовать рандом в 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

Methods

Modifier and TypeMethod and Description
protected intnext(int bits)

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

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

Источник

Java – Generate random integers in a range

By mkyong | Last updated: August 19, 2015

Viewed: 825,482 (+1,265 pv/w)

Как использовать рандом в java. java random integer in range. Как использовать рандом в java фото. Как использовать рандом в java-java random integer in range. картинка Как использовать рандом в java. картинка java random integer in range

In this article, we will show you three ways to generate random integers in a range.

1. java.util.Random

This Random().nextInt(int bound) generates a random integer from 0 (inclusive) to bound (exclusive).

1.2 What is (max – min) + 1) + min?

Above formula will generates a random integer in a range between min (inclusive) and max (inclusive).

1.3 Full examples to generate 10 random integers in a range between 5 (inclusive) and 10 (inclusive).

2. Math.random

This Math.random() gives a random double from 0.0 (inclusive) to 1.0 (exclusive).

2.1 Code snippet. Refer to 1.2, more or less it is the same formula.

2.2 Full examples to generate 10 random integers in a range between 16 (inclusive) and 20 (inclusive).

3. Java 8 Random.ints

In Java 8, new methods are added in java.util.Random

This Random.ints(int origin, int bound) or Random.ints(int min, int max) generates a random integer from origin (inclusive) to bound (exclusive).

3.2 Full examples to generate 10 random integers in a range between 33 (inclusive) and 38 (inclusive).

3.3 Extra, for self-reference.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

I find a little error,as
1.3 Full examples to generate 10 random integers in a range between 5 (inclusive) and 10 (inclusive).
java doc is
nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
Thank you all the same!

How to generate dynamic regex for numeric range in java

Why do we use limit(1) in below snippet? Using only findFirst() should return single random integer, isn’t it?
r.ints(min, (max + 1)).limit(1).findFirst().getAsInt()

i dont know. Dont ask me.

Thank you, I have just been searching for info about this subject for a long time and yours is the greatest I’ve found out so far. However, what about the bottom line? Are you positive concerning the supply? ceefcffkaakbbkkg

Thanks, Worked to me. Looks precise.

1.3 code snippet (max – min) + 1 will not work if max parameter is Integer.MAX_VALUE

how to make Integer.MAX_VALUE inclusive? Impossible?

static int getRandomNumberInRange(int min, int max) <
if (min >= max) <
throw new IllegalArgumentException(“max must be greater than min”);
>

I cant make Integer.MAX_VALUE inclusive, but at least it will work with Integer.MAX_VALUE as max paramenter exclusive.

The only thing I can do is this but that’s not what I need

Random random = new Random();
int rand = random.nextInt(100);
int rand1 =(-100 + random.nextInt(100));

Is there an explanation of why the first one works? I get how it works but why it does 😀

How can I save the generated numbers as integers (variables)? The console says “intstreams can’t be converted to int”

This code is the easiest way to return 10 random numbers between 1 and 99. I took all your ideas and came up with this brief but effective code. Just change the values of 99,1,1 to your min and max to get your #s. If you use 99 as your max, randomly 99 + 1 will make the code generate 100, so if you really want max of 99, use 98 in this code. 😀

* @author balcopc
*/
import java.util.Random;
public class RandomNumberProj <

public static void main(String[] args) <
System.out.println(“Random Numbers: “);

//print ten random numbers between 1 and 99
Random r = new Random();

Источник

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

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

1) java.util.Random

// Java-программа для демонстрации генерации случайных чисел
// используя java.util.Random;

public class generateRandom<

public static void main(String args[])

// создаем экземпляр класса Random

Random rand = new Random();

// Генерируем случайные целые числа в диапазоне от 0 до 999

int rand_int1 = rand.nextInt( 1000 );

int rand_int2 = rand.nextInt( 1000 );

// Вывести случайные целые числа

System.out.println( «Random Integers: » +rand_int1);

System.out.println( «Random Integers: » +rand_int2);

// Генерируем случайные числа

double rand_dub1 = rand.nextDouble();

double rand_dub2 = rand.nextDouble();

// Выводим случайные числа

System.out.println( «Random Doubles: » +rand_dub1);

System.out.println( «Random Doubles: » +rand_dub2);

// Java-программа для демонстрации работы
// Math.random () для генерации случайных чисел

public class generateRandom

public static void main(String args[])

// Генерация случайных двойников

System.out.println( «Random doubles: » + Math.random());

System.out.println( «Random doubles: » + Math.random());

3) класс java.util.concurrent.ThreadLocalRandom
Этот класс введен в Java 1.7 для генерации случайных чисел типа integer, double, boolean и т. Д. Ниже программа объясняет, как использовать этот класс для генерации случайных чисел:

// Java-программа для демонстрации работы ThreadLocalRandom
// генерировать случайные числа.

public class generateRandom

public static void main(String args[])

// Генерируем случайные целые числа в диапазоне от 0 до 999

int rand_int1 = ThreadLocalRandom.current().nextInt();

int rand_int2 = ThreadLocalRandom.current().nextInt();

// Вывести случайные целые числа

System.out.println( «Random Integers: » + rand_int1);

System.out.println( «Random Integers: » + rand_int2);

// Генерируем случайные числа

double rand_dub1 = ThreadLocalRandom.current().nextDouble();

double rand_dub2 = ThreadLocalRandom.current().nextDouble();

// Выводим случайные числа

System.out.println( «Random Doubles: » + rand_dub1);

System.out.println( «Random Doubles: » + rand_dub2);

// Генерируем случайные логические значения

boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean();

boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean();

// Печать случайных логических значений

System.out.println( «Random Booleans: » + rand_bool1);

System.out.println( «Random Booleans: » + rand_bool2);

Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.

Источник

Вводный курс. Язык программирования Java

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

Существует несколько способов генерации случайного (псевдослучайного) числа:

Рассмотрим методы генерации случайных чисел.

Класс Math. Метод random()

Метод random() класса Math возвращает псевдослучайное число типа double в диапазоне 0 ≤ Math.random()

Пример 1. Несколько случайных чисел

Случайное число № 1: 0.9161994380531232
Случайное число № 2: 0.24340742865928744
Случайное число № 3: 0.9783627451986034

Пример 2. Случайное число x в диапазоне a ≤ x ≤ b

Для генерации целого случайного числа x в заданном диапазоне a ≤ x ≤ b, обычно используется следующая зависимость:

Получим случайное число x в диапазоне: 10 ≤ x ≤ 20 (a=10, b=20).

Результат.
Случайное число x: 19

Класс Random. Метод random()

Основными методами этого класса являются:

Для получения случайных чисел необходимо:

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

Случайное число ix: 1438841988 Случайное число dx: 0.6120986135409442 Случайное число fx: 0.103119016 Случайное число bx: true

Пример 2. Случайное число x в диапазоне a ≤ x ≤ b.

Для генерации целого случайного числа x в заданном диапазоне a ≤ x ≤ b, обычно используется следующая зависимость:

Случайное число x: 12 Случайное число dx: 17.505847041626733

Для типа double будет выведено случайное число в виде:

что неудобно. Для приемлемого представления используется форматный вывод, позволяющий выводить числа с заданной точностью.

Форматный вывод

System.out.format(String format, Object. args),

Источник

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

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