Get a random number focused on center

后端 未结 20 2989
离开以前
离开以前 2020-12-12 09:28

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 main

相关标签:
20条回答
  • 2020-12-12 09:50

    The best way to do that is generating a random number that is distributed equally in a certain set of numbers, and then apply a projection function to the set between 0 and a 100 where the projection is more likely to hit the numbers you want.

    Typically the mathematical way of achieving this is plotting a probability function of the numbers you want. We could use the bell curve, but let's for the sake of easier calculation just work with a flipped parabola.

    Let's make a parabola such that its roots are at 0 and 100 without skewing it. We get the following equation:

    f(x) = -(x-0)(x-100) = -x * (x-100) = -x^2 + 100x
    

    Now, all the area under the curve between 0 and 100 is representative of our first set where we want the numbers generated. There, the generation is completely random. So, all we need to do is find the bounds of our first set.

    The lower bound is, of course, 0. The upper bound is the integral of our function at 100, which is

    F(x) = -x^3/3 + 50x^2
    F(100) = 500,000/3 = 166,666.66666 (let's just use 166,666, because rounding up would make the target out of bounds)
    

    So we know that we need to generate a number somewhere between 0 and 166,666. Then, we simply need to take that number and project it to our second set, which is between 0 and 100.

    We know that the random number we generated is some integral of our parabola with an input x between 0 and 100. That means that we simply have to assume that the random number is the result of F(x), and solve for x.

    In this case, F(x) is a cubic equation, and in the form F(x) = ax^3 + bx^2 + cx + d = 0, the following statements are true:

    a = -1/3
    b = 50
    c = 0
    d = -1 * (your random number)
    

    Solving this for x yields you the actual random number your are looking for, which is guaranteed to be in the [0, 100] range and a much higher likelihood to be close to the center than the edges.

    0 讨论(0)
  • 2020-12-12 09:51

    You can use a helper random number to whether generate random numbers in 40-60 or 1-100:

    // 90% of random numbers should be between 40 to 60.
    var weight_percentage = 90;
    
    var focuse_on_center = ( (Math.random() * 100) < weight_percentage );
    
    if(focuse_on_center)
    {
    	// generate a random number within the 40-60 range.
    	alert (40 + Math.random() * 20 + 1);
    }
    else
    {
    	// generate a random number within the 1-100 range.
    	alert (Math.random() * 100 + 1);
    }

    0 讨论(0)
提交回复
热议问题