Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Do you really know how js generates random numbers?

Shulou Source: shulou.com Published: 2022-06-01 06:46:38 10月03日 Update

The basis of all random numbers generated by js is Math.random (). This method is special. The generated random number falls in an interval [0L1). If you perform one operation, js can only generate an interval like [nPermine m), which is closed on the left and open on the right. So when there are some special needs, it is necessary to do some other operations, the following is a simple analysis of the various requirements:

Generate integers with arbitrary intervals

Fully closed interval [nPermim]

The most common, well-known long list of formulas: Math.floor (Math.random () * (m-n+1)) + n; is the way to generate this fully closed interval. Speaking of this formula, many people know it, but few people really want to figure it out. You can make an interval like this, and then use Math.floor () to get any integer between [0rem _ m\ n] (it is very important to see this step), and then add the left end point of the interval to any integer in [njue m] to achieve the goal.

Speaking of this place, there is one point that must be mentioned. If you randomly search js to generate random numbers, many articles will use the two methods of Math.ceil () or Math.round (), such as generating any integer in the completely closed [n Math.random m] interval, Math.ceil (Math.random () * (MMMI n)) + n; or Math.round (Math.random () * (MMI n)) + n I feel that the most important thing in random numbers is random words, and the probability of each value must be equal, which is very important for some specific occasions, such as a lucky draw (there is a lucky draw every year). The problem with Math.ceil () is n

Tags: Interval generation integer random number formula method probability important two that is fault point characteristic endpoint demand facet special consistent difficult necessary Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Huawei Microsoft OPPO Reno MySQL