Math.random()

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 Math.random() between 1 to N

By default Math.random() always generates numbers between 0.0 to 1.0, but if we want to get numbers within a specific range then we have to multiple the return value with the magnitude of the range.

Example:- If we want to generate number between 1 to 100 using the Math.random() then we must multiply the returned value by 100.

Java program to generate floating-point numbers between 1 to 100.

Output:-

10.48550810115520481.26887023085449

The above program generates floating-point numbers but if we want to generate integer numbers then we must type cast the result value.

Java program to generate integer numbers between 1 to 100.

Output:-

2070

Math и метод random

Вроде бы всё просто, вызвал свойство у объекта и вот тебе числа. Но не всё так просто, это конечно не чистый природный рандом а эмулятор, псевдо-рандом. Но и он поможет написать вам интересную программу, например русское лото.

Но генерирует он числа от 0 до 1, так что разберём нюансы написания скрипта и вызова random, так же наполним массив случайными числами.

JavaScript

<script>
var rand = Math.random(); //Но минус в том что генерирует он от нуля до единицы
document.write(rand);

document.write(«<br /><hr />»);

var rand2 = Math.random() * 100; //Так мы получим случайное число в диапазоне от 0 до 100
document.write(rand2);

document.write(«<br /><hr />»);

var rand3 = Math.round(Math.random() * 100); //Наконец то нормальное человеческое число))
document.write(rand3);

document.write(«<br /><hr />»);

//Теперь нам надо задать диапазон в котором числа будут рандомизировать, здесь вам пришлось бы повозиться если бы всё ещё до вас не придумали
function myRandom(from, to){
return Math.floor((Math.random() * (to — from + 1)) + from); //Тут уже нужны математические мозги
}

document.write(myRandom(50,60));

/**********************************************************************************************************************/
//Заполняем массив рандомными числами

var randArr = new Array(10);
var start = 40;
var fin = 80;

function myRandom2(from, to){
return Math.floor((Math.random() * (to — from + 1)) + from); //Тут уже нужны математические мозги
}

function randomArray(arr,begin,end){
for(var i = 0; i < arr.length; i++){
arr = myRandom2(begin,end); //Так просто 0_о!!! В смысле я думал понадобиться метод типа push
document.write(arr + «<br />»);
}
}

document.write(«<br /><hr />Значения в массиве формируются от » + start + » и до » + fin + «<br />»);
randomArray(randArr,start,fin); //Можно спрограммировать игру «русское лото» какие числа будут выпадать
</script>

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

<script>

varrand=Math.random();//Но минус в том что генерирует он от нуля до единицы

document.write(rand);

document.write(«<br /><hr />»);

varrand2=Math.random()*100;//Так мы получим случайное число в диапазоне от 0 до 100

document.write(rand2);

document.write(«<br /><hr />»);

varrand3=Math.round(Math.random()*100);//Наконец то нормальное человеческое число))

document.write(rand3);

document.write(«<br /><hr />»);

//Теперь нам надо задать диапазон в котором числа будут рандомизировать, здесь вам пришлось бы повозиться если бы всё ещё до вас не придумали

functionmyRandom(from,to){

returnMath.floor((Math.random()*(to-from+1))+from);//Тут уже нужны математические мозги

}

document.write(myRandom(50,60));

 
/**********************************************************************************************************************/
//Заполняем массив рандомными числами
 

varrandArr=newArray(10);

varstart=40;

varfin=80;

functionmyRandom2(from,to){

returnMath.floor((Math.random()*(to-from+1))+from);//Тут уже нужны математические мозги

}

functionrandomArray(arr,begin,end){

for(vari=;i<arr.length;i++){

arri=myRandom2(begin,end);//Так просто 0_о!!! В смысле я думал понадобиться метод типа push

document.write(arri+»<br />»);

}

}

document.write(«<br /><hr />Значения в массиве формируются от «+start+» и до «+fin+»<br />»);

randomArray(randArr,start,fin);//Можно спрограммировать игру «русское лото» какие числа будут выпадать

</script>

Количество просмотров: 402

| Категория: JavaScript | Тэги: JavaScript / random / основы / числа

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

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()
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
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

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()

Using Math.random() to generate random number between 1 and 10

You can also use method to random number between 1 and 10. You can iterate from min to max and use Math.ran
Here is formula for the same:

1
2
3

intrandomNumber=(int)(Math.random()*(max-min))+min;

 

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

publicclassMathRandomExample

{

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=(int)(Math.random()*(max-min))+min;

System.out.println(randomNumber);

}

}

}
 

============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
9
6
5
6
2

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.)

How to generate random numbers in Java?

We can use the  static method of the Math class to generate random numbers in Java.

1 publicstaticdoublerandom()

This method returns a double number that is greater than or equal to 0.0 and less than 1.0 (Please note that the 0.0 is inclusive while 1.0 is exclusive so that 0 <= n < 1)

a) How to generate a random number between 0 and 1?

1
2
3
4
5
6
7
8
9
10
11
12
13

packagecom.javacodeexamples.mathexamples;

publicclassGenerateRandomNumberExample{

publicstaticvoidmain(Stringargs){

System.out.println(«Random numbers between 0 and 1»);

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

System.out.println(Math.random());

}

}

}

Output (could be different for you as these are random numbers)

1
2
3
4
5
6
7
8
9
10
11
Random numbers between 0 and 1
0.12921328590853476
0.7936354242494305
0.08878870565069197
0.12470497778455492
0.1738593303254422
0.6793228890529989
0.5948655601179271
0.9910316469070309
0.1867838198026388
0.6630122474512686

b) Between 0 and 100

It is a fairly easy task to generate random numbers between 0 and 100. Since the  method returns a number between 0.0 and 1.0, multiplying it with 100 and casting the result to an integer will give us a random number between 0 and 100 (where 0 is inclusive while 100 is exclusive).

1
2

intrandomNumber=(int)(Math.random()*100);

System.out.println(«Random Number: «+randomNumber);

c) Between a specific range

Since the  method returns a double value between 0.0 and 1.0, we need to derive a formula so that we can generate numbers in the specific range.

Let’s do that step by step. Suppose you want to generate random numbers between 10 and 20. So the minimum number it should generate is 10 and the maximum number should be 20.

Step 1:

First of all, we need to multiply the  method result with the maximum number so that it returns value between 0 to max value (in this case 20) like given below.

1 intrandomNumber=(int)(Math.random()*20);

The above statement will return us a random number between 0.0 and 19. That is because multiplying 0.0 – 0.99 with 20 and casting the result back to int will give us the range of 0 to 19.

Step 2:

Step 1 gives us a random number between 0 and 19. But we want a random number starting from 10, not 0. Let’s add that number to the result.

1 intrandomNumber=10+(int)(Math.random()*20);

Step 3:

Now the number starts from 10 but it goes up to 30. That is because adding 10 to 0-19 will give us 10-29. So let’s subtract 10 from 20 before the multiplication operation.

1 intrandomNumber=10+(int)(Math.random()*(20-10));

Step 4:

The random number generated by the above formula gives us a range between 10 and 19 (both inclusive). The number range we wanted was between 10 and 20 (both inclusive). So let’s add 1 to the equation.

1 intrandomNumber=10+(int)(Math.random()*((20-10)+1));

A final result is a random number in the range of 10 to 20.

Git Essentials

Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!

95

И если вы хотите генерировать последовательности, можно создать вспомогательный метод:

public static List intsInRange(int size, int lowerBound, int upperBound) {
    SecureRandom random = new SecureRandom();
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add(random.nextInt(upperBound - lowerBound) + lowerBound);
    }
    return result;
}

Которые вы можете использовать в качестве:

List integerList =  intsInRange3(5, 0, 10);
System.out.println(integerList);

И что приводит к:

Математика.случайная()

Класс предоставляет нам отличные вспомогательные методы, связанные с математикой. Одним из них является метод , который возвращает случайное значение в диапазоне . Как правило, он используется для генерации случайных значений процентиля.

Тем не менее, аналогично взлом – вы можете использовать эту функцию для генерации любого целого числа в определенном диапазоне:

int min = 10;
int max = 100;

int randomNumber = (int)(Math.random() * (max + 1 - min) + min);
System.out.println(randomNumber);

Хотя этот подход еще менее интуитивен, чем предыдущий. Выполнение этого кода приводит к чему-то вроде:

43

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

public static List intsInRange(int size, int lowerBound, int upperBound) {
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add((int)(Math.random() * (upperBound + 1 - lowerBound) + lowerBound));
    }
    return result;
}

И тогда мы можем назвать это так:

List integerList =  intsInRange(5, 0, 10);
System.out.println(integerList);

Который производит:

ThreadLocalRandom.nextInt()

Если вы работаете в многопоточной среде, класс предназначен для использования в качестве потокобезопасного эквивалента . К счастью, он предлагает метод nextInt () как верхней, так и нижней границей:

int randomInt = ThreadLocalRandom.current().nextInt(0, 10);
System.out.println(randomInt);

Как обычно, нижняя граница включена, в то время как верхняя граница отсутствует:

3

Аналогично, вы можете создать вспомогательную функцию для создания последовательности этих:

public static List intsInRange(int size, int lowerBound, int upperBound) {
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add(ThreadLocalRandom.current().nextInt(lowerBound, upperBound));
    }
    return result;
}

Которые вы можете использовать в качестве:

List integerList = intsInRange4(5, 0, 10);
System.out.println(integerList);

SplittableRandom.ints()

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

Стоит отметить, что этот класс также основан на небезопасной генерации семян-если вы ищете безопасную генерацию семян, используйте .

Класс предлагает метод , который, с нашей точки зрения, работает так же, как :

List intList = new SplittableRandom().ints(5, 1, 11)
        .boxed()
        .collect(Collectors.toList());

System.out.println(intList);

Что приводит к:

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

int randomInt = new SplittableRandom().ints(1, 1, 11).findFirst().getAsInt();
System.out.println(randomInt);

Что приводит к:

4

Вывод

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

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

Using Apache Common lang

You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.

Create AlphaNumericString

You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

packageorg.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

publicclassApacheRandomStringMain{

publicstaticvoidmain(Stringargs){

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

}

}
 

Output:

Generating String of length 10: Wvxj2x385N
Generating String of length 10: urUnMHgAq9
Generating String of length 10: 8TddXvnDOV

Create random Alphabetic String

You can use RandomStringUtils.randomAlphabetic method to generate alphanumeric random strn=ing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

packageorg.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

publicclassApacheRandomStringMain{

publicstaticvoidmain(Stringargs){

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

}

}
 

Output:

Generating String of length 10: zebRkGDuNd
Generating String of length 10: RWQlXuGbTk
Generating String of length 10: mmXRopdapr

That’s all about generating Random String in java.

The Rolling Dice Game

In this section, we will create a really simple mini dice game. Two players enter their name and will roll the dice. The player whose dice has a higher number will win the round.

First, create a function that simulates the action for rolling the dice.

Inside the function body, call the function with and as the arguments. This will give you any random number between 1 and 6 (both inclusive) just like how real dice would work.

Next, create two input fields and a button as shown below:

When the ‘Roll Dice’ button is clicked, get the player names from the input fields and call the function for each player.

You can validate the players’ name fields and prettify the markup with some CSS. For the purpose of brevity, I’m keeping it simple for this guide.

That is it. You can check out the demo here.

Other Pseudo-Random Number Generators

Crypto.getRandomValues()

Cryptographically strong pseudo-random values are available on all web browsers that support . Implementations vary across user agents, but all are required to use a seed with enough entropy. To fill an array with results try:

The Middle Square Method

Invented by John von Neumann around 1946, the Middle Square Method (MSM) generates a pseudo-random number sequence by extracting the middle digits from a squared number.

Beware of certain seed values, like 25, which have a shorter cycle or cause the algorithm to repeat one value indefinitely.

Linear Congruential Generator

Invented around 1958 by Thomson & Rotenberg, the Linear Congruential Generator (LGC) algorithm is perhaps the oldest-known. It’s fast, and when care is taken with the initial values, quite adequate.

Xorshift family of pseudo-random number generators

Xorshift or “shift-register generators” are a family of pseudorandom number generators that were discovered by George Marsaglia in 2003. Among the fastest PRNGs, they use bitwise operations to deliver a high-quality sequence.

The xorshift variants —  xorwow, xorshift+, xoshiro, xoroshiro, xoshiro256*, xoshiro256+ — each provide a different method; research into the suitability of each of these for your needs is time well spent.

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.

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

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

Adblock
detector