Генерация случайных чисел
Содержание:
- Способы случайной генерации строк в java (три)
- Random Number Generator in Java
- What to read next
- Generating Javascript Random Numbers More Easily
- The Math.random() method
- API
- Random number generation in more detail
- Why is this needed?
- JavaScript
- Random Number Generator Function
- Генерация случайных чисел с помощью класса Math
- Java Math.random Between Two Numbers
- True Random Numbers
- Java Random Class
- What is Randomness in Javascript?
- Заключение
Способы случайной генерации строк в java (три)
http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>style=»clear:both;»>
1. Первый типКаждая позиция сгенерированной строки может быть буквой или числом в строке str. Пакет, который необходимо импортировать, — это import java.util.Random;
2. Второй типВы можете указать местоположение как a-z, A-Z или 0-9, а импортируемый пакет — import java.util.Random;
3. Третий типВ пакете org.apache.commons.lang есть класс RandomStringUtils, который имеет функцию randomAlphanumeric (int length), которая может произвольно генерировать строку длины length.
// Создание 5-значной случайной строки, которая искажена в китайской среде RandomStringUtils.random(5);
// Используйте указанные символы для генерации случайной строки длиной 5 бит RandomStringUtils.random(5, new char[]{‘a’,’b’,’c’,’d’,’e’,’f’, ‘1’, ‘2’, ‘3’});
// Создание случайной комбинации букв и цифр указанной длины RandomStringUtils.randomAlphanumeric(5);
// Генерируем строку случайных чисел RandomStringUtils.randomNumeric(5);
// Генерация случайной строки , включая регистр RandomStringUtils.randomAlphabetic(5);
// Генерируем случайную строку от 32 до 126 ASCII RandomStringUtils.randomAscii(4)
Интеллектуальная рекомендация
содержание 1, основная функция MPI 2, точка-точка функция связи 3, коллективная функция связи 1, основная функция MPI MPI_Init(&argc, &argv) Информировать системы MPI для выполнения всех необх…
EL выражение…
концепция Виртуальная машина JVM управляет собственной памятью, которая разделяет память во многие блоки, наиболее распространенной для памяти стека и памяти кучи. 1 структура виртуальной машины JVM H…
вЗапустите Android 9 (API Уровень 28) или вышеНа устройстве операционной системы Android, чтобы обеспечить безопасность пользовательских данных и устройств, использование по умолчанию для зашифрованно…
предисловие Для изучения веб-пакета автор также предпринял много обходных путей. Есть много вещей, которые я хочу знать, но я не могу их найти. Автор поможет вам быстро начать работу. Цель этой статьи…
Вам также может понравиться
The ALPC company is now working on his own network system, which is connecting all N ALPC department. To economize on spending, the backbone network has only one router for each department, and N-1 op…
Метафизический разрез, просто просмотрите поиск Я чувствую, что процедура поиска состоит в том, чтобы сначала набрать общую структуру, а затем шаг за шагом оптимизировать процесс сокращения. 1. Длина …
Используйте Maven для запуска модульных тестов Чтобы запустить модульные тесты через Maven, введите эту команду: Это запустит весь модульный тест в вашем проекте. Тематическое исследование Создайте дв…
Построить HTTP-сервис Как TCP, так и UDP являются протоколами транспортного уровня в сети, но если вы хотите создавать эффективные сетевые приложения, вам следует начать с транспортного уровня. Для об…
…
Random Number Generator in Java
There are many ways to generate a random number in java.
- java.util.Random class can be used to create random numbers. It provides several methods to generate random integer, long, double etc.
- We can also use Math.random() to generate a double. This method internally uses Java Random class.
- class should be used to generate random number in multithreaded environment. This class is part of Java Concurrent package and introduced in Java 1.7. This class has methods similar to Java Random class.
- can be used to generate random number with strong security. This class provides a cryptographically strong random number generator. However, it’s slow in processing. So depending on your application requirements, you should decide whether to use it or not.
What to read next
The following pages contain further information on the ranodm number generators listed above, as well as
further alternatives:
- ThreadLocalRandom
- SecureRandom
1. These sources of «physical» randomness or «real unpredictability» are generally referred to as entropy.
Clock time is the most common source, but other sources could include e.g. CPU temperature
sensors, noise from analogue sound card inputs, timings from physical disk activity (in the age of spinny disks at least!),
recent mouse movement etc. With each of these sources, there are whole discussions to be had on how
good a source of entropy they are.
1. What we’re describing here is sometimes more specifically called
a uniform random number generator. We could equally have a generator where
numbers occur randomly with some non-linear distribution.
For example, in a later section, we discuss generating
numbers with a normal distribution, which is needed in certain simulation
applications.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey
Editorial page content written by Neil Coffey. Copyright Javamex UK 2021. All rights reserved.
Generating Javascript Random Numbers More Easily
is a useful function, but on its own it doesn’t give programmers an easy way to generate pseudo-random numbers for specific conditions. There may be a need to generate random numbers in a specific range that doesn’t start with 0, for example.
Fortunately, there are simple functions that programmers can create to make pseudo-random numbers more manageable. The rest of this section will show you how to create those functions, then put them all together into a single pseudo-random number generator.
Integer Pseudo-Random Numbers Across A Range
In the previous examples, could never create a number at the very top of a specified range. If you wanted a number between 0 and 5, for example, you could get 0-4, but never 5. The solution to this problem, if you’re creating an integer, is adding 1 to the result.
Since floating point numbers in Javascript go out to many decimal places, there isn’t a simple one-number solution to include the maximum possible floating point number in your range unless you want to make shaky assumptions and type a lot of zeroes. Instead, you can use some simple math that also works with integers to get pseudo-random numbers all across your range.
Floating-Point Pseudo-Random Numbers Across A Range
A function that does this for floating point numbers would look almost identical, except that it wouldn’t use :
Floating point numbers remain a little tricky here because by default generates the maximum number of decimal places the Javascript implementation allows. In most circumstances, you probably want to cap your decimal places at 3 or 4 instead of reading the 10 or more that usually creates.
Floating-Point Pseudo-Random Numbers With Specific Decimal Places
The function formats a number with the number of decimal places you specify. To make sure that you don’t accidentally create a string in some Javascript implementations, it’s best to always chain with the function.
Putting It All Together
Putting all of this together, a Javascript pseudo-random number generator that can create integers or floating point numbers with any number of decimal places could look like this. (Note that this implementation also includes error checking for the parameters.)
The Math.random() method
The object in JavaScript is a built-in object that has properties and methods for performing mathematical calculations.
A common use of the object is to create a random number using the method.
But the method doesn’t actually return a whole number. Instead, it returns a floating-point value between 0 (inclusive) and 1 (exclusive). Also, note that the value returned from is pseudo-random in nature.
Random numbers generated by might seem random, but those numbers will repeat and eventually display a non-random pattern over a period of time.
This is because algorithmic random number generation can never be truly random in nature. This is why we call them pseudo-random number generators (PRNGs).
To learn more about the method you can check out this guide.
API
- : Utilizes
- : Utilizes
- : Utilizes
- : Produces a new Mersenne Twister. Must be seeded before use.
Or you can make your own!
interfaceEngine{next()number;}
Any object that fulfills that interface is an .
- : Seed the twister with an initial 32-bit integer.
- : Seed the twister with an array of 32-bit integers.
- : Seed the twister with automatic information. This uses the current Date and other entropy sources.
- : Produce a 32-bit signed integer.
- : Discard random values. More efficient than running repeatedly.
- : Return the number of times the engine has been used plus the number of discarded values.
One can seed a Mersenne Twister with the same value () or values () and discard the number of uses () to achieve the exact same state.
If you wish to know the initial seed of , it is recommended to use the function to create the seed manually (this is what does under-the-hood).
constseed=createEntropy();constmt=MersenneTwister19937.seedWithArray(seed);useTwisterALot(mt);constclone=MersenneTwister19937.seedWithArray(seed).discard(mt.getUseCount());
Random.js also provides a set of methods for producing useful data from an engine.
- : Produce an integer within the inclusive range . can be at its minimum -9007199254740992 (-2 ** 53). can be at its maximum 9007199254740992 (2 ** 53).
- : Produce a floating point number within the range . Uses 53 bits of randomness.
- : Produce a boolean with a 50% chance of it being .
- : Produce a boolean with the specified chance causing it to be .
- : Produce a boolean with / chance of it being true.
- : Return a random value within the provided within the sliced bounds of and .
- : Same as .
- : Shuffle the provided (in-place). Similar to .
- : From the array, produce an array with elements that are randomly chosen without repeats.
- : Same as
- : Produce an array of length with as many rolls.
- : Produce a random string using numbers, uppercase and lowercase letters, , and of length .
- : Produce a random string using the provided string as the possible characters to choose from of length .
- or : Produce a random string comprised of numbers or the characters of length .
- : Produce a random string comprised of numbers or the characters of length .
- : Produce a random within the inclusive range of . and must both be s.
An example of using would be as such:
constengine=MersenneTwister19937.autoSeed();constdistribution=integer(,99);functiongenerateNaturalLessThan100(){returndistribution(engine);}
Producing a distribution should be considered a cheap operation, but producing a new Mersenne Twister can be expensive.
An example of producing a random SHA1 hash:
var engine = nativeMath;var distribution =hex(false);functiongenerateSHA1(){returndistribution(engine,40);}
Random number generation in more detail
The simple line of code above glosses over a lot of complexity.
We want to produce «unpredictable» numbers yet the whole point of computer instructions is that,
for a given input, they are designed to produce a predictable
result. So random number generation algorithms must generally take whatever tiny amount of «physical» randomness
might be available, e.g. the current clock time in milliseconds or nanoseconds1, and then use this as a
seed to generate a sequence that to the observer, appears to be unpredictable.
As well as being unpredictable, we generally want computer-genreated random numbers to have similar statistical
properties to the «real» sources of unpredictability they are simulating. For example, if we write a
routine to simulate rolling a six-sided dice, we would like each of the numbers 1-6 to
come up with equal probability. And if the routine is used to generate two rolls in succession, we would
like it to appear as though the two rolls were completely independent, just as if we were rolling two
physical dice.
In some cases, we need random numbers to be so unpredictable that money or the security of a system depend on it
(i.e. they are cryptographically secure).
For example, if we assign a random encryption key to one user of a web site or remote system, we don’t want that user to be able to
determine the next user’s encryption key based on the one assigned to them.
A large number of random number generation techniques have been devised over the years to address the above needs. Each one is
generally a tradeoff: how much CPU time and memory usage are we willing to dedicate to achieving the
goals of statistical fairness and unpredictability given our intended use?
Java includes various
random number generators in the standard JDK, and makes it relatively staightforward to plug in additional
algorithms if required.
Why is this needed?
Despite being capable of producing numbers within [0, 1), there are a few downsides to doing so:
- It is inconsistent between engines as to how many bits of randomness:
- Internet Explorer: 53 bits
- Mozilla Firefox: 53 bits
- Google Chrome/node.js: 32 bits
- Apple Safari: 32 bits
- It is non-deterministic, which means you can’t replay results consistently
- In older browsers, there can be manipulation through cross-frame random polling. This is mostly fixed in newer browsers and is required to be fixed in ECMAScript 6.
Also, and most crucially, most developers tend to use improper and biased logic as to generating integers within a uniform distribution.
JavaScript
JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()
JS Boolean
constructor
prototype
toString()
valueOf()
JS Classes
constructor()
extends
static
super
JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()
JS Error
name
message
JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()
JS JSON
parse()
stringify()
JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sinh()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()
JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()
JS OperatorsJS RegExp
Modifiers:
g
i
m
Groups:
(x|y)
Metacharacters:
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx
Quantifiers:
+
*
?
{X}
{X,Y}
{X,}
$
^
?=
?!
Properties:
constructor
global
ignoreCase
lastIndex
multiline
source
Methods:
compile()
exec()
test()
toString()
JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while
JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()
Random Number Generator Function
Now let’s use the method to create a function that will return a random integer between two values (inclusive).
Let’s break down the logic here.
The method will return a floating-point number between 0 and 1 (exclusive).
So the intervals would be as follows:
To factor the second interval, subtract min from both ends. So that would give you an interval between 0 and .
So now, to get a random value you would do the following:
Here is the random value.
Currently, is excluded from the interval. To make it inclusive, add 1. Also, you need to add the back that was subtracted earlier to get a value between .
Alright, so now the last step remaining is to make sure that is always an integer.
You could use the method instead of , but that would give you a non-uniform distribution. This means that both and will have half a chance to come out as an outcome. Using will give you perfectly even distribution.
So now that you have a fair understanding of how a random generation works, let’s use this function to simulate rolling dice.
Генерация случайных чисел с помощью класса 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
Разобьем это выражение на части:
- Сначала умножаем диапазон значений на результат, который генерирует метод random().Math.random() * (max — min)возвращает значение в диапазоне , где max не входит в заданные рамки. Например, выражение Math.random()*5 вернет значение в диапазоне , в который 5 не входит.
- Расширяем охват до нужного диапазона. Это делается с помощью минимального значения.
(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 Math.random Between Two Numbers
The method does not accept any arguments, which means that there is no way to influence the number generated by the method. However, we can create our own method which allows us to generate numbers between a particular range.
For instance, suppose we are building an app that generates the random numbers which will be used to distinguish a customer’s order at a cruise line. These numbers will be added onto the end of a customer’s name.
The number we want to generate should be between 200 and 500. In order to generate this number and prepare the customer’s order reference, we could use this code:
class Main { public static int generateTicketNumber(int min, int max) { int range = (max - min) + 1; return (int)(Math.random() * range) + min; } public static void main(String args[]) { String customerName = "JohnMcIver"; int randomNumber = generateTicketNumber(200, 500); System.out.println(customerName + randomNumber); } }
Our code returns:
In our program, we generate a random number between the range of 200 and 500. Then we append that number to the customer’s name and print out the result to the console.
Let’s break down how our code works:
- We declare a method called which accepts two parameters: min and max.
- uses the min and max parameters to generate a random number within the range of those two numbers with
- When the main program runs, a variable called is declared and is assigned the value .
- Then the method is called and the parameters 200 and 500 are specified, which correspond to the min and max values in the range our result should fall in, respectively. The result of this method is assigned to the variable .
- The customer’s name and the random number generated are concatenated—or merged together—and printed to the console.
True Random Numbers
As mentioned above, true random numbers must spring for a source outside computers without hardware dedicated to this purpose. For needs that require truly random cryptographically appropriate random numbers use one of the following external sources via their public APIs:
- random.org samples atmospheric noise and provides several data sources: integer, sequence, set, gaussian, float, and raw random data.
- The Australian National University (ANU) Quantum Optics Group’s Quantum RNG derives random numbers by measuring the quantum fluctuations of a vacuum. Additionally, you can see and hear random number sequences.
- The Ruđer Bošković Institute Quantum Random Bit Generator Service harvests randomness from the quantum process of photonic emission in semiconductors, made available through many libraries for programming languages and other methods.
- The Taiyuan University of Technology Physical Random Number Generator Service publishes random numbers sourced from a chaotic laser.
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:
- : creates new random generator
- : 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.
- : This method returns next pseudorandom which is a boolean value from random number generator sequence.
- : This method returns next pseudorandom which is double value between 0.0 and 1.0.
- : This method returns next pseudorandom which is float value between 0.0 and 1.0.
- : This method returns next int value from random number generator sequence.
- 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
What is Randomness in Javascript?
It is impossible in computing to generate completely random numbers. This is because every calculation inside a computer has a logical basis of cause and effect, while random events don’t follow that logic.
Computers are not capable of creating something truly random. True randomness is only possible through a source of external data that a computer cannot generate, such as the movement of many lava lamps at once (which has been used as an unbreakable random encryption in the real world), meteographic noise, or nuclear decay.
The solution that Javascript, and other programming languages, use to implement randomness is “pseudo-random” number generation. Javascript random numbers start from a hidden internal value called a “seed.” The seed is a starting point for a hidden sequence of numbers that are uniformly distributed throughout their possible range.
Developers cannot change Javascript’s pseudo-random seed or the distribution of values in its generated pseudo-random sequences. Different Javascript implementations and different browsers often start with different seeds. Do not assume that different browsers, or even different computers, will always use the same seed.
Javascript random numbers are not safe for use in cryptography because deciphering the seed could lead to decryption of the hidden number sequence. Some functions exist to create cryptographically secure pseudo-random numbers in Javascript, but they are not supported by older browsers.
In this blog post, we’ll first cover the canonical methods of creating Javascript random numbers. Then we’ll move onto ways of obtaining higher-quality random data; your needs will determine the worthwhile effort.
Заключение
Класс java.util.Random реализует линейный конгруэнтный генератор (LCG). Он отличается быстротой работы. Но при этом он не подходит для использования в режиме реального времени. Например, для генерации уникального идентификатора сессии на сервере, в научных экспериментах, криптографии лотереях и розыгрышах.
Пожалуйста, оставьте свои комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, отклики, дизлайки, лайки, подписки!
Пожалуйста, оставляйте ваши отзывы по текущей теме материала. За комментарии, отклики, лайки, дизлайки, подписки огромное вам спасибо!
Вадим Дворниковавтор-переводчик статьи «Random Number Generation in Java»