Home > Article > Web Front-end > Analysis of the process of generating random numbers with js_javascript skills
1. Preliminary knowledge
Math.ceil(); //向上取整。 Math.floor(); //向下取整。 Math.round(); //四舍五入。 Math.random(); //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //比如0.8647578968666494 Math.ceil(Math.random()*10); // 获取从1到10的随机整数 ,取0的概率极小。 Math.round(Math.random()); //可均衡获取0到1的随机整数。 Math.floor(Math.random()*10); //可均衡获取0到9的随机整数。 Math.round(Math.random()*10); //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
Because the result is 0~0.4, 0.5 to 1.4 is 1...8.5 to 9.4 is 9, and 9.5 to 9.9 is 10. Therefore, the distribution interval of the head and tail is only half that of other numbers.
2. Generate random integers of [n, m]
Function: Generate random integers of [n, m].
It is useful when js generates verification code or randomly selects an option. .
//生成从minNum到maxNum的随机数 function randomNum(minNum,maxNum){ switch(arguments.length){ case 1: return parseInt(Math.random()*minNum+1,10); break; case 2: return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); break; default: return 0; break; } }
Process Analysis:
Math.random() generates the number [0,1), so Math.random()*5 generates the number {0,5).
Usually an integer is expected, so the result needs to be processed.
parseInt(), Math.floor(), Math.ceil() and Math.round() can all get integers.
The results of parseInt() and Math.floor() are rounded down.
So Math.random()*5 generates random integers in [0,4].
So the random number of [1,max] is generated, the formula is as follows:
// max - 期望的最大值 parseInt(Math.random()*max,10)+1; Math.floor(Math.random()*max)+1; Math.ceil(Math.random()*max);
So generate a random number from [0,max] to any number, the formula is as follows:
// max - 期望的最大值 parseInt(Math.random()*(max+1),10); Math.floor(Math.random()*(max+1));
So I hope to generate a random number of [min, max], the formula is as follows:
// max - 期望的最大值 // min - 期望的最小值 parseInt(Math.random()*(max-min+1)+min,10); Math.floor(Math.random()*(max-min+1)+min);
The above is a comprehensive analysis of random numbers generated by js. It is very detailed. I hope it can help everyone.