Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Do you really know how js generates random numbers?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report