J
J
jslby2018-12-16 12:12:56
JavaScript
jslby, 2018-12-16 12:12:56

How to implement random numbers in a large range in js?

It is necessary to implement random numbers in a large range. About 80 characters per number. Standard solutions like Math.rand do not provide the required entropy.
It is the algorithm that is needed, because even the libraries from npm do not give the desired result when working like with bigint.
A small algorithm has matured:
Get a number as a string and split it into separate numbers.
Within each number, get a random number from 0 to the current number.
Add as a string and get a random slice from 1 to the number of characters in the original number.
The option is not bad, but it will count unevenly. There are far fewer options for random numbers in a number with a length of 10 characters than in a number with a length of 80 characters. But in fact, they will go the same way with the probability of a random choice. Those. the number 100 will have the same probability of appearing as the number 100000000.
This is due to the cutoff. According to the idea, a certain probability multiplier is needed, which will determine how large the number is and let's have more probabilities of choice in its range.
How can you write an algorithm that will calculate as accurately as possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2018-12-16
@Rsa97

function rand80() {
  let result = ''+Math.floor(Math.random()*10000000000);
  for (let i = 0; i < 7; i++) {
    result += ('0000000000'+Math.floor(Math.random()*10000000000)).substr(-10);
  }
  return result;
}
console.log(rand80());

78687700753019149846288536942965286843811762227419373094448469993291737449820343

S
Sumor, 2018-12-16
@Sumor

2^256 is about 78 decimal places
. Take a 256-bit crypto algorithm: you can use AES, or you can use SHA256 (you can't decrypt it). You take an initializing value - you count the value - here you have 256 almost random bits. You add something else to the initializing value - you get the following, and so on

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question