Get a random number focused on center

后端 未结 20 3043
离开以前
离开以前 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:41

    You can write a function that maps random values between [0, 1) to [1, 100] according to weight. Consider this example:

    0.0-1.0 to 1-100 by percentage weight

    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], yields 81.

    Here is the function:

    /*
     * Function that returns a function that maps random number to value according to map of probability
     */
    function createDistributionFunction(data) {
      // cache data + some pre-calculations
      var cache = [];
      var i;
      for (i = 0; i < data.length; i++) {
        cache[i] = {};
        cache[i].valueMin = data[i].values[0];
        cache[i].valueMax = data[i].values[1];
        cache[i].rangeMin = i === 0 ? 0 : cache[i - 1].rangeMax;
        cache[i].rangeMax = cache[i].rangeMin + data[i].weight;
      }
      return function(random) {
        var value;
        for (i = 0; i < cache.length; i++) {
          // this maps random number to the bracket and the value inside that bracket
          if (cache[i].rangeMin <= random && random < cache[i].rangeMax) {
            value = (random - cache[i].rangeMin) / (cache[i].rangeMax - cache[i].rangeMin);
            value *= cache[i].valueMax - cache[i].valueMin + 1;
            value += cache[i].valueMin;
            return Math.floor(value);
          }
        }
      };
    }
    
    /*
     * Example usage
     */
    var distributionFunction = createDistributionFunction([
      { weight: 0.1, values: [1, 40] },
      { weight: 0.8, values: [41, 60] },
      { weight: 0.1, values: [61, 100] }
    ]);
    
    /*
     * Test the example and draw results using Google charts API
     */
    function testAndDrawResult() {
      var counts = [];
      var i;
      var value;
      // run the function in a loop and count the number of occurrences of each value
      for (i = 0; i < 10000; i++) {
        value = distributionFunction(Math.random());
        counts[value] = (counts[value] || 0) + 1;
      }
      // convert results to datatable and display
      var data = new google.visualization.DataTable();
      data.addColumn("number", "Value");
      data.addColumn("number", "Count");
      for (value = 0; value < counts.length; value++) {
        if (counts[value] !== undefined) {
          data.addRow([value, counts[value]]);
        }
      }
      var chart = new google.visualization.ColumnChart(document.getElementById("chart"));
      chart.draw(data);
    }
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(testAndDrawResult);
    
    

提交回复
热议问题