首页 > 解决方案 > 如何从 JavaScript 的 Math.random 生成包含有界的帕累托随机整数

问题描述

来自维基百科

在此处输入图像描述

我试图实现这个公式,即使它基于使用均匀分布在 (0,1) 上的随机数并产生分数,而 JavaScript 中的 Math.random 在 [0,1) 上产生数字,我正在寻找整数没有成功:

function getRandomIntInclusivePareto(min, max, alpha = 1) {
  const u = Math.random();
  const x =
    (-(
    (u * max ** alpha - u * min ** alpha - max ** alpha) / 
    (max ** alpha * min ** alpha)
    )) ** -(1 / alpha);

  return x;
}

console.log(getRandomIntInclusivePareto(0, 1024));

什么公式(或者更好的代码)可以让我使用 Math.random 生成包含有界的随机帕累托整数?

我正在寻找这种 API:

function getRandomParetoIntInclusive(min, max, alpha = 1)

标签: javascriptrandomstatisticsdistribution

解决方案


好的,首先你的代码中有一个错误,你不能包含 0,console.log(getRandomIntInclusivePareto(0, 1024)不会工作。

其次,要获得整数,您必须将整数和样本值的概率计算为离散分布。您提供的公式和代码用于连续采样,不适用于离散帕累托。要进行离散采样,您必须设置样本列表(或范围)及其概率。我正在使用https://github.com/jacobmenick/sampling代码进行离散采样。概率是通过帕累托分布计算的。只需从链接中复制代码并将其放在下面的代码段顶部即可运行。

节点 12.1,x64 Win10

function getRandomIntInclusivePareto(min, max, alpha = 1.0) {
    var probabilities = []; // probabilities 
    for (var k = min; k <= max; ++k) {
        probabilities.push(1.0/Math.pow(k, alpha)); // computed according to Paretto
    }                                               // would be normalized by SJS

    var disc = SJS.Discrete(probabilities); // discrete sampler, returns value in the [0...probabilities.length-1] range
    q = disc.draw() + min; // back to [min...max] interval

    return q;
}

console.log("Testing Paretto");

var t = getRandomIntInclusivePareto(1, 10, 1.3);

console.log(t);

推荐阅读