admin管理员组文章数量:1399912
I want to implement a random number generator which lets me set the maximum number I want but also lets me tweak the probabilities to make it harder to get bigger number.
Using this would allocate the same probabilities to any value in the range of 100.
Math.floor(Math.random()*100);
How can I make numbers get progressively harder to appear as the number gets closer to the limit (100)?
I want to implement a random number generator which lets me set the maximum number I want but also lets me tweak the probabilities to make it harder to get bigger number.
Using this would allocate the same probabilities to any value in the range of 100.
Math.floor(Math.random()*100);
How can I make numbers get progressively harder to appear as the number gets closer to the limit (100)?
Share Improve this question edited Dec 7, 2012 at 16:45 Peter O. 32.9k14 gold badges85 silver badges97 bronze badges asked Dec 7, 2012 at 6:25 lisovaccarolisovaccaro 34.1k99 gold badges271 silver badges423 bronze badges 3- 1 And thus calculus was reborn once again. – Erik Reppen Commented Dec 7, 2012 at 6:46
- How much progressively harder? How many more 0's do you expect than 99s? Also, btw here you range is actualy 0 to 99. You will never get 100. if you want to go from 0 to 100, multiple by 101. If you want to go from 1 to 100, multiply by 100 and add 1 (or use ceiling instead of floor). – frankc Commented Dec 7, 2012 at 19:42
- I've always needed something like this! Great question! Oh, by the way, I don't think your code can actually generate the number 100. Try using 101, since the range of Math.random() is 0 to 1, but 1 in exclusive (It will never appear). – rydwolf Commented Oct 29, 2018 at 1:09
3 Answers
Reset to default 6Square the result of Math.random
:
var result = Math.random();
result = result * result;
result *= 100;
result = Math.floor(result);
You can adjust the curve by adjusting the exponent. Here's a few graphs of different exponents:
If you're going to use a non-integer exponent, you'll need to use Math.pow
.
Simply use a mathematically function that has curve giving you the required probability weighting. For example, you could 'square' your number:
var num = Math.pow(Math.floor(Math.random()*10), 2);
The above generates a random number between 1-10 then squares it to give a random number between 1-100, but weighted towards lower numbers.
You can further increase the weighting by using higher power.
Math.pow(Math.floor(Math.random()*10), 2);
Or something similar.
本文标签: javascriptGenerate random numbers with less probabilities of bigger numbersStack Overflow
版权声明:本文标题:javascript - Generate random numbers with less probabilities of bigger numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744242085a2596837.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论