最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generate random numbers with less probabilities of bigger numbers - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

Square 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.

发布评论

评论列表(0)

  1. 暂无评论