Generating random numbers in java

Содержание:

Java Random Class

  • class is part of java.util package.
  • An instance of java Random class is used to generate random numbers.
  • This class provides several methods to generate random numbers of type integer, double, long, float etc.
  • Random number generation algorithm works on the seed value. If not provided, seed value is created from system nano time.
  • If two Random instances have same seed value, then they will generate same sequence of random numbers.
  • Java Random class is thread-safe, however in multithreaded environment it’s advised to use class.
  • Random class instances are not suitable for security sensitive applications, better to use in those cases.

Java Random Constructors

Java Random class has two constructors which are given below:

  1. : creates new random generator
  2. : creates new random generator using specified seed

Java Random Class Methods

Let’s have a look at some of the methods of java Random class.

  1. : This method returns next pseudorandom which is a boolean value from random number generator sequence.
  2. : This method returns next pseudorandom which is double value between 0.0 and 1.0.
  3. : This method returns next pseudorandom which is float value between 0.0 and 1.0.
  4. : This method returns next int value from random number generator sequence.
  5. nextInt(int n): This method return a pseudorandom which is int value between 0 and specified value from random number generator sequence.

Java Random Example

Let’s have a look at the below java Random example program.

Output of the above program is:

Check this post for more about Java Radom Number Generation.

Generate Random Number using Seed

There are two ways we can generate random number using seed.

The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).

Output of the above program is:

What if we pass same seed to two different random number generators?

Let’s have a look at the below program and see what happen if we pass same seed to two different random number generators.

Output of the above program is:

We can see that it will generate same random number if we pass same seed to two different random number generators.

Java 8 Random Class Methods

As you can see from above image, there are many new methods added in Java 8 to Random class. These methods can produce a stream of random numbers. Below is a simple program to generate a stream of 5 integers between 1 and 100.

That’s all for a quick roundup on Java Random Class.

Reference: API Doc

Random Numbers Using the Math Class

Java provides the Math class in the java.util package to generate random numbers.

The Math class contains the static Math.random() method to generate random numbers of the double type.

The random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. When you call Math.random(), under the hood, a java.util.Random pseudorandom-number generator object is created and used.

You can use the Math.random() method with or without passing parameters. If you provide parameters, the method produces random numbers within the given parameters.

The code to use the Math.random() method:

The getRandomNumber() method uses the Math.random() method to return a positive double value that is greater than or equal to 0.0 and less than 1.0.

The output of running the code is:

Random Numbers Within a Given Range

For generating random numbers between a given a range, you need to specify the range. A standard expression for accomplishing this is:

Let us break this expression into steps:

  1. First, multiply the magnitude of the range of values you want to cover by the result that Math.random() produces.returns a value in the range ,max–min where max is excluded. For example, if you want 5,10], you need to cover 5 integer values so you can use Math.random()*5. This would return a value in the range ,5, where 5 is not included.
  2. Next, shift this range up to the range that you are targeting. You do this by adding the min value.

But this still does not include the maximum value.

To get the max value included, you need to add 1 to your range parameter (max — min). This will return a random double within the specified range.

There are different ways of implementing the above expression. Let us look at a couple of them.

Random Double Within a Given Range

By default, the Math.random() method returns a random number of the type double whenever it is called. The code to generate a random double value between a specified range is:

You can call the preceding method from the main method by passing the arguments like this.

The output is this.

Random Integer Within a Given Range

The code to generate a random integer value between a specified range is this.

The preceding getRandomIntegerBetweenRange() method produces a random integer between the given range. As Math.random() method generates random numbers of double type, you need to truncate the decimal part and cast it to int in order to get the integer random number. You can call this method from the main method by passing the arguments as follows:

The output is this.

Note: You can pass a range of negative values to generate a random negative number within the range.

Method Summary

All MethodsInstance MethodsConcrete Methods

Modifier and Type Method Description
Returns an effectively unlimited stream of pseudorandom values, each between zero (inclusive) and one
(exclusive).
Returns an effectively unlimited stream of pseudorandom values, each conforming to the given origin (inclusive) and bound
(exclusive).
Returns a stream producing the given number of
pseudorandom values, each between zero
(inclusive) and one (exclusive).
Returns a stream producing the given number of
pseudorandom values, each conforming to the given origin
(inclusive) and bound (exclusive).
Returns an effectively unlimited stream of pseudorandom
values.
Returns an effectively unlimited stream of pseudorandom values, each conforming to the given origin (inclusive) and bound
(exclusive).
Returns a stream producing the given number of
pseudorandom values.
Returns a stream producing the given number
of pseudorandom values, each conforming to the given
origin (inclusive) and bound (exclusive).
Returns an effectively unlimited stream of pseudorandom
values.
Returns a stream producing the given number of
pseudorandom values.
Returns an effectively unlimited stream of pseudorandom values, each conforming to the given origin (inclusive) and bound
(exclusive).
Returns a stream producing the given number of
pseudorandom , each conforming to the given origin
(inclusive) and bound (exclusive).
Generates the next pseudorandom number.
Returns the next pseudorandom, uniformly distributed
value from this random number generator’s
sequence.
Generates random bytes and places them into a user-supplied
byte array.
Returns the next pseudorandom, uniformly distributed
value between and
from this random number generator’s sequence.
Returns the next pseudorandom, uniformly distributed
value between and from this random
number generator’s sequence.
Returns the next pseudorandom, Gaussian («normally») distributed
value with mean and standard
deviation from this random number generator’s sequence.
Returns the next pseudorandom, uniformly distributed
value from this random number generator’s sequence.
Returns a pseudorandom, uniformly distributed value
between 0 (inclusive) and the specified value (exclusive), drawn from
this random number generator’s sequence.
Returns the next pseudorandom, uniformly distributed
value from this random number generator’s sequence.
Sets the seed of this random number generator using a single
seed.

Random Number Generation Using the Random Class

You can use the java.util.Random class to generate random numbers of different types, such as int, float, double, long, and boolean.

To generate random numbers, first, create an instance of the Random class and then call one of the random value generator methods, such as nextInt(), nextDouble(), or nextLong().

The nextInt() method of Random accepts a bound integer and returns a random integer from 0 (inclusive) to the specified bound (exclusive).

The code to use the nextInt() method is this.

The code to use the nextInt() method to generate an integer within a range is:

The nextFloat() and nextDouble() methods allow generating float and double values between 0.0 and 1.0.

The code to use both the methods is:

Using ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10

If you want to generate random number in current thread, you can use to generate random number between 1 and 10.

was introducted in JDK 7 for managing multiple threads.

Let’s see with the help of example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

import java.util.concurrent.ThreadLocalRandom;

publicclassThreadLocalRandomNextIntMain

{

publicstaticvoidmain(Stringargs){

intmin=1;

intmax=10;

System.out.println(«============================»);

System.out.println(«Generating 10 random integer in range of 1 to 10 using Math.random»);

System.out.println(«============================»);

for(inti=;i<5;i++){

intrandomNumber=ThreadLocalRandom.current().nextInt(min,max)+min;

System.out.println(randomNumber);

}

}

}
 

============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
7
7
4
10
4

That’s all about java random number between 1 and 10.

Using Java API

The Java API provides us with several ways to achieve our purpose. Let’s see some of them.

2.1. java.lang.Math

The random method of the Math class will return a double value in a range from 0.0 (inclusive) to 1.0 (exclusive). Let’s see how we’d use it to get a random number in a given range defined by min and max:

2.2. java.util.Random

Before Java 1.7, the most popular way of generating random numbers was using nextInt. There were two ways of using this method, with and without parameters. The no-parameter invocation returns any of the int values with approximately equal probability. So, it’s very likely that we’ll get negative numbers:

If we use the netxInt invocation with the bound parameter, we’ll get numbers within a range:

This will give us a number between 0 (inclusive) and parameter (exclusive). So, the bound parameter must be greater than 0. Otherwise, we’ll get a java.lang.IllegalArgumentException.

Java 8 introduced the new ints methods that return a java.util.stream.IntStream. Let’s see how to use them.

The ints method without parameters returns an unlimited stream of int values:

We can also pass in a single parameter to limit the stream size:

And, of course, we can set the maximum and minimum for the generated range:

2.3. java.util.concurrent.ThreadLocalRandom

Java 1.7 release brought us a new and more efficient way of generating random numbers via the ThreadLocalRandom class. This one has three important differences from the Random class:

  • We don’t need to explicitly initiate a new instance of ThreadLocalRandom. This helps us to avoid mistakes of creating lots of useless instances and wasting garbage collector time
  • We can’t set the seed for ThreadLocalRandom, which can lead to a real problem. If we need to set the seed, then we should avoid this way of generating random numbers
  • Random class doesn’t perform well in multi-threaded environments

Now, let’s see how it works:

With Java 8 or above, we have new possibilities. Firstly, we have two variations for the nextInt method:

Secondly, and more importantly, we can use the ints method:

2.4. java.util.SplittableRandom

Java 8 has also brought us a really fast generator — the SplittableRandom class.

As we can see in the JavaDoc, this is a generator for use in parallel computations. It’s important to know that the instances are not thread-safe. So, we have to take care when using this class.

We have available the nextInt and ints methods. With nextInt we can set directly the top and bottom range using the two parameters invocation:

This way of using checks that the max parameter is bigger than min. Otherwise, we’ll get an IllegalArgumentException. However, it doesn’t check if we work with positive or negative numbers. So, any of the parameters can be negative. Also, we have available one- and zero-parameter invocations. Those work in the same way as we have described before.

We have available the ints methods, too. This means that we can easily get a stream of int values. To clarify, we can choose to have a limited or unlimited stream. For a limited stream, we can set the top and bottom for the number generation range:

2.5. java.security.SecureRandom

If we have security-sensitive applications, we should consider using SecureRandom. This is a cryptographically strong generator. Default-constructed instances don’t use cryptographically random seeds. So, we should either:

  • Set the seed — consequently, the seed will be unpredictable
  • Set the java.util.secureRandomSeed system property to true

This class inherits from java.util.Random. So, we have available all the methods we saw above. For example, if we need to get any of the int values, then we’ll call nextInt without parameters:

On the other hand, if we need to set the range, we can call it with the bound parameter:

We must remember that this way of using it throws IllegalArgumentException if the parameter is not bigger than zero.

Игра в кости с использованием модуля random в Python

Далее представлен код простой игры в кости, которая поможет понять принцип работы функций модуля random. В игре два участника и два кубика.

  • Участники по очереди бросают кубики, предварительно встряхнув их;
  • Алгоритм высчитывает сумму значений кубиков каждого участника и добавляет полученный результат на доску с результатами;
  • Участник, у которого в результате большее количество очков, выигрывает.

Код программы для игры в кости Python:

Python

import random

PlayerOne = «Анна»
PlayerTwo = «Алекс»

AnnaScore = 0
AlexScore = 0

# У каждого кубика шесть возможных значений
diceOne =
diceTwo =

def playDiceGame():
«»»Оба участника, Анна и Алекс, бросают кубик, используя метод shuffle»»»

for i in range(5):
#оба кубика встряхиваются 5 раз
random.shuffle(diceOne)
random.shuffle(diceTwo)
firstNumber = random.choice(diceOne) # использование метода choice для выбора случайного значения
SecondNumber = random.choice(diceTwo)
return firstNumber + SecondNumber

print(«Игра в кости использует модуль random\n»)

#Давайте сыграем в кости три раза
for i in range(3):
# определим, кто будет бросать кости первым
AlexTossNumber = random.randint(1, 100) # генерация случайного числа от 1 до 100, включая 100
AnnaTossNumber = random.randrange(1, 101, 1) # генерация случайного числа от 1 до 100, не включая 101

if( AlexTossNumber > AnnaTossNumber):
print(«Алекс выиграл жеребьевку.»)
AlexScore = playDiceGame()
AnnaScore = playDiceGame()
else:
print(«Анна выиграла жеребьевку.»)
AnnaScore = playDiceGame()
AlexScore = playDiceGame()

if(AlexScore > AnnaScore):
print («Алекс выиграл игру в кости. Финальный счет Алекса:», AlexScore, «Финальный счет Анны:», AnnaScore, «\n»)
else:
print(«Анна выиграла игру в кости. Финальный счет Анны:», AnnaScore, «Финальный счет Алекса:», AlexScore, «\n»)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

importrandom

PlayerOne=»Анна»

PlayerTwo=»Алекс»

AnnaScore=

AlexScore=

 
# У каждого кубика шесть возможных значений

diceOne=1,2,3,4,5,6

diceTwo=1,2,3,4,5,6

defplayDiceGame()

«»»Оба участника, Анна и Алекс, бросают кубик, используя метод shuffle»»»

foriinrange(5)

#оба кубика встряхиваются 5 раз

random.shuffle(diceOne)

random.shuffle(diceTwo)

firstNumber=random.choice(diceOne)# использование метода choice для выбора случайного значения

SecondNumber=random.choice(diceTwo)

returnfirstNumber+SecondNumber

print(«Игра в кости использует модуль random\n»)

 
#Давайте сыграем в кости три раза

foriinrange(3)

# определим, кто будет бросать кости первым

AlexTossNumber=random.randint(1,100)# генерация случайного числа от 1 до 100, включая 100

AnnaTossNumber=random.randrange(1,101,1)# генерация случайного числа от 1 до 100, не включая 101

if(AlexTossNumber>AnnaTossNumber)

print(«Алекс выиграл жеребьевку.»)

AlexScore=playDiceGame()

AnnaScore=playDiceGame()

else

print(«Анна выиграла жеребьевку.»)

AnnaScore=playDiceGame()

AlexScore=playDiceGame()

if(AlexScore>AnnaScore)

print(«Алекс выиграл игру в кости. Финальный счет Алекса:»,AlexScore,»Финальный счет Анны:»,AnnaScore,»\n»)

else

print(«Анна выиграла игру в кости. Финальный счет Анны:»,AnnaScore,»Финальный счет Алекса:»,AlexScore,»\n»)

Вывод:

Shell

Игра в кости использует модуль random

Анна выиграла жеребьевку.
Анна выиграла игру в кости. Финальный счет Анны: 5 Финальный счет Алекса: 2

Анна выиграла жеребьевку.
Анна выиграла игру в кости. Финальный счет Анны: 10 Финальный счет Алекса: 2

Алекс выиграл жеребьевку.
Анна выиграла игру в кости. Финальный счет Анны: 10 Финальный счет Алекса: 8

1
2
3
4
5
6
7
8
9
10

Игравкостииспользуетмодульrandom

 
Аннавыигралажеребьевку.

Аннавыигралаигрувкости.ФинальныйсчетАнны5ФинальныйсчетАлекса2

 
Аннавыигралажеребьевку.

Аннавыигралаигрувкости.ФинальныйсчетАнны10ФинальныйсчетАлекса2

 
Алексвыигралжеребьевку.

Аннавыигралаигрувкости.ФинальныйсчетАнны10ФинальныйсчетАлекса8

Вот и все. Оставить комментарии можете в секции ниже.

Core team and contributors

Awesome contributors

  • Adriano Machado
  • Alberto Lagna
  • Andrew Neal
  • Aurélien Mino
  • Arne Zelasko
  • dadiyang
  • Dovid Kopel
  • Eric Taix
  • euZebe
  • Fred Eckertson
  • huningd
  • Johan Kindgren
  • Joren Inghelbrecht
  • Jose Manuel Prieto
  • kermit-the-frog
  • Lucas Andersson
  • Michael Düsterhus
  • Nikola Milivojevic
  • nrenzoni
  • Oleksandr Shcherbyna
  • Petromir Dzhunev
  • Rebecca McQuary
  • Rodrigue Alcazar
  • Ryan Dunckel
  • Sam Van Overmeire
  • Valters Vingolds
  • Vincent Potucek
  • Weronika Redlarska
  • Konstantin Lutovich
  • Steven_Van_Ophem
  • Jean-Michel Leclercq
  • Marian Jureczko
  • Unconditional One
  • JJ1216
  • Sergey Chernov

Thank you all for your contributions!

Random Time

Similar to what we did with dates, we can generate random temporals with just time components. In order to do that, we can use the second of the day concept. That is, a random time is equal to a random number representing the seconds since the beginning of the day.

4.1. Bounded

The java.time.LocalTime class is a temporal abstraction that encapsulates nothing but time components:

In order to generate a random time between two others, we can:

  1. Generate a random number between the second of the day of the given times
  2. Create a random time using that random number

We can easily verify the behavior of this random time generation algorithm:

4.2. Unbounded

Even unbounded time values should be in 00:00:00 until 23:59:59 range, so we can simply implement this logic by delegation:

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

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

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

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

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

public static double getRandomNumber(){
    double x = Math.random();
    return x;
}

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

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

Double between 0.0 and 1.0: SimpleRandomNumber = 0.21753313144345698

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

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

(Math.random() * ((max - min) + 1)) + min

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

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

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

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

double x = (Math.random()*((max-min)+1))+min;

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

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

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

public static double getRandomDoubleBetweenRange(double min, double max){
    double x = (Math.random()*((max-min)+1))+min;
    return x;
}

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

System.out.println("Double between 5.0 and 10.00: RandomDoubleNumber = 
"+getRandomDoubleBetweenRange(5.0, 10.00));

Результат.

System.out.println("Double between 5.0 and 10.00: RandomDoubleNumber = 
"+getRandomDoubleBetweenRange(5.0, 10.00));

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

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

public static double getRandomIntegerBetweenRange(double min, double max){
    double x = (int)(Math.random()*((max-min)+1))+min;
    return x;
}

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

System.out.println("Integer between 2 and 6: RandomIntegerNumber 
= "+getRandomIntegerBetweenRange(2,6));

Результат.

Integer between 2 and 6: RandomIntegerNumber = 5

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

Пример

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

Все классы-оболочки (Integer, Long, Byte, Double, Float, Short) являются подклассами абстрактного класса чисел в Java (class Number).

Объект класса-оболочки содержит или обертывает свой соответствующих примитивный тип данных. Конвертирование примитивных типов данных в объект называется упаковка, и об этом заботится компилятором. Поэтому при использовании класса-оболочки необходимо просто передать конструктору класса-оболочки значение примитивного типа данных.

Объект оболочки может быть преобразован обратно в примитивный тип данных, и этот процесс называется распаковка. Класс чисел является частью пакета java.lang.

Вот пример упаковки и распаковки:

Будет получен следующий результат:

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

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

Для генерирования целочисленных псевдослучайных значений используется представленное выше выражение, в котором
произведение «приводится» к целочисленному значению. Например, попробуем получить псевдослучайное значение в диапазоне

Обратите внимание, что закрывающаяся скобка квадратная, т.е. 20 входит в диапазон

В этом случае к разности
между максимальным и минимальным значениями следует добавить 1, т.е. определить диапазон целочисленных значений [5,21),
где 21 не попадает в желаемый диапазон :

// после подстановки значений
int i = (int)Math.random() * (20 - 5 + 1) + 5;
// получаем
int i = (int)Math.random() * 16 + 5;

Latest news

  • 15/11/2020: Easy Random v5.0.0 is out and is now based on Java 11. Feature wise, this release is the same as v4.3.0. Please check the release notes for more details.
  • 07/11/2020: Easy Random v4.3.0 is now released with support for generic types and fluent setters! You can find all details in the change log.

What is Easy Random ?

EasyRandom easyRandom = new EasyRandom();
Person person = easyRandom.nextObject(Person.class);

The method is able to generate random instances of any given type.

What is this EasyRandom API ?

The API provides 7 methods to generate random data: , , , , , and .
What if you need to generate a random ? Or say a random instance of your domain object?
Easy Random provides the API that extends with a method called .
This method is able to generate a random instance of any arbitrary Java bean.

The class is the main entry point to configure instances. It allows you to set all
parameters to control how random data is generated:

EasyRandomParameters parameters = new EasyRandomParameters()
   .seed(123L)
   .objectPoolSize(100)
   .randomizationDepth(3)
   .charset(forName("UTF-8"))
   .timeRange(nine, five)
   .dateRange(today, tomorrow)
   .stringLengthRange(5, 50)
   .collectionSizeRange(1, 10)
   .scanClasspathForConcreteTypes(true)
   .overrideDefaultInitialization(false)
   .ignoreRandomizationErrors(true);

EasyRandom easyRandom = new EasyRandom(parameters);

For more details about these parameters, please refer to the configuration parameters section.

In most cases, default options are enough and you can use the default constructor of .

Easy Random allows you to control how to generate random data through the interface and makes it easy to exclude some fields from the object graph using a :

EasyRandomParameters parameters = new EasyRandomParameters()
   .randomize(String.class, () -> "foo")
   .excludeField(named("age").and(ofType(Integer.class)).and(inClass(Person.class)));

EasyRandom easyRandom = new EasyRandom(parameters);
Person person = easyRandom.nextObject(Person.class);

In the previous example, Easy Random will:

  • Set all fields of type to (using the defined as a lambda expression)
  • Exclude the field named of type in class .

The static methods , and are defined in
which provides common predicates you can use in combination to define exactly which fields to exclude.
A similar class called can be used to define which types to exclude from the object graph.
You can of course use your own in combination with those predefined predicates.

Why Easy Random ?

Populating a Java object with random data can look easy at first glance, unless your domain model involves many related classes. In the previous example, let’s suppose the type is defined as follows:

Without Easy Random, you would write the following code in order to create an instance of the class:

Street street = new Street(12, (byte) 1, "Oxford street");
Address address = new Address(street, "123456", "London", "United Kingdom");
Person person = new Person("Foo", "Bar", "foo.bar@gmail.com", Gender.MALE, address);

And if these classes do not provide constructors with parameters (may be some legacy beans you can’t change), you would write:

Street street = new Street();
street.setNumber(12);
street.setType((byte) 1);
street.setName("Oxford street");

Address address = new Address();
address.setStreet(street);
address.setZipCode("123456");
address.setCity("London");
address.setCountry("United Kingdom");

Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
person.setEmail("foo.bar@gmail.com");
person.setGender(Gender.MALE);
person.setAddress(address);

With Easy Random, generating a random object is done with .
The library will recursively populate all the object graph. That’s a big difference!

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

Модуль Python UUID предоставляет неизменяемые UUID объекты. UUID является универсально уникальным идентификатором.

У модуля есть функции для генерации всех версий UUID. Используя функцию , можно получить случайно сгенерированное уникальное ID длиной в 128 битов, которое к тому же является криптографически надежным.

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

Пример использования в Python:

Python

import uuid

# получить уникальный UUID
safeId = uuid.uuid4()
print(«безопасный уникальный id «, safeId)

1
2
3
4
5
6

importuuid

 
 
# получить уникальный UUID

safeId=uuid.uuid4()

print(«безопасный уникальный id «,safeId)

Вывод:

Shell

безопасный уникальный id fb62463a-cd93-4f54-91ab-72a2e2697aff

1 безопасныйуникальныйidfb62463a-cd93-4f54-91ab-72a2e2697aff

Модуль random

Для того, чтобы полноценно использовать эту опцию в своей работе, необходимо ознакомится с главными ее составляющими. Они выступают некими методами, позволяющими выполнять определенные действия. Основная стандартная библиотека Рython состоит из таких компонентов со следующими параметрами:

  • random () – может вернуть число в промежуток значений от 0 до 1;
  • seed (a) – производит настройку генератора на новую последовательность а;
  • randint (a,b) – возвращает значение в диапазон данных от а до b;
  • randrange (a, b, c) – выполняет те же функции, что и предыдущая, только с шагом с;
  • uniform (a, b) – производит возврат вещественного числа в диапазон от а до b;
  • shuffle (a) – миксует значения, находящиеся в перечне а;
  • choice (a) – восстанавливает обратно случайный элемент из перечня а;
  • sample (a, b) – возвращает на исходную позицию последовательность длиной b из перечня а;
  • getstate () – обновляет внутреннее состояние генератора;
  • setstate (a) – производит восстановление внутреннего состояния генератора а;
  • getrandbits (a) – восстанавливает а при выполнении случайного генерирования бит;
  • triangular (a, b, c) – показывает изначальное значение числа от а до b с шагом с.

Если вам необходимо применить для задания инициализирующееся число псевдо случайной последовательности, то не обойтись без функции seed. После ее вызова без применения параметра, используется значение системного таймера. Эта опция доступна в конструкторе класса Random.

Более показательными будут примеры на основе вышеописанного материала. Для возможности воспользоваться генерацией случайных чисел в Рython 3, сперва вам потребуется выполнить импорт библиотеки random, внеся сперва ее в начало исполняемого файла при помощи ключевого слова import.

Вещественные числа

Модуль оснащен одноименной функцией random. Она более активно используется в Питоне, чем остальные. Эта функция позволяет произвести возврат числа в промежуток значений от 0 до 1. Вот пример трех основных переменных:

import randoma = random.random()b = random.random()print(a)print(b)

0.5479332865190.456436031781

Целые числа

Чтобы в программе появились случайные числа из четко заданного диапазона, применяется функция randit. Она обладает двумя аргументами: максимальным и минимальным значением. Она отображает значения, указанные ниже в генерации трех разных чисел от 0 до 9.

import randoma = random.randint(0, 9)b = random.randint(0, 9)print(a)print(b)

47

Диапазон целых чисел

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

  • минимальное значение;
  • максимальное;
  • длина шага.

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

import randoma = random.randrange(10)b = random.randrange(2, 10)c = random.randrange(2, 10, 2)print(a)print(b)print(c)

952

Диапазон вещественных чисел

Генерация вещественных чисел происходит при использовании функции под названием uniform. Она регулируется всего двумя параметрами: минимальным и максимальным значением. Пример создания демонстрации с переменными a, b и c.

import randoma = random.uniform(0, 10)b = random.uniform(0, 10)print(a)print(b)

4.856873750913.66695202551

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

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

Adblock
detector