Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be mainly within that range... Is it possible with JavaScript/jQuery?
Right now I'm just using the basic Math.random() * 100 + 1
.
I needed to solve this problem a few years ago and my solution was easier than any of the other answers.
I generated 3 randoms between the bounds and averaged them. This pulls the result towards the centre but leaves it completely possible to reach the extremities.
You can write a function that maps random values between
[0, 1)
to[1, 100]
according to weight. Consider this example:Here, the value
0.95
maps to value between[61, 100]
.In fact we have
.05 / .1 = 0.5
, which, when mapped to[61, 100]
, yields81
.Here is the function:
Ok, so I decided to add another answer because I felt like my last answer, as well as most answers here, use some sort of half-statistical way of obtaining a bell-curve type result return. The code I provide below works the same way as when you roll a dice. Therefore, it is hardest to get 1 or 99, but easiest to get 50.
I'd recommend using the beta distribution to generate a number between 0-1, then scale it up. It's quite flexible and can create many different shapes of distributions.
Here's a quick and dirty sampler:
You have some good answers here that give specific solutions; let me describe for you the general solution. The problem is:
The general solution to this problem is to work out the quantile function of your desired distribution, and then apply the quantile function to the output of your uniform source.
The quantile function is the inverse of the integral of your desired distribution function. The distribution function is the function where the area under a portion of the curve is equal to the probability that the randomly-chosen item will be in that portion.
I give an example of how to do so here:
http://ericlippert.com/2012/02/21/generating-random-non-uniform-data/
The code in there is in C#, but the principles apply to any language; it should be straightforward to adapt the solution to JavaScript.
This answer is really good. But I would like to post implementation instructions (I'm not into JavaScript, so I hope you will understand) for different situation.
Assume you have ranges and weights for every range:
Initial Static Information, could be cached:
Boundary[n] = Boundary[n - 1] + weigh[n - 1]
andBoundary[0] = 0
. Sample hasBoundary = {0, 1, 3, 103, 108}
Number generation:
N
from range [0, Sum of all weights).for (i = 0; i < size(Boundary) && N > Boundary[i + 1]; ++i)
i
th range and generate random number in that range.Additional note for performance optimizations. Ranges don't have to be ordered neither ascending nor descending order, so for faster range look-up range that has highest weight should go first and one with lowest weight should go last.