来自 Wikipedia :
我试图实现这个公式,即使它基于使用均匀分布在 (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 生成包含边界的随机 Pareto 整数?
我正在寻找这种 API:
function getRandomParetoIntInclusive(min, max, alpha = 1)
最佳答案
好的,首先你的代码中有一个错误,你不能包含 0,console.log(getRandomIntInclusivePareto(0, 1024)
将不起作用。
其次,要获得整数,您必须计算整数和样本值作为离散分布的概率。您提供的公式和代码用于 连续采样,它不适用于离散 Paretto。要进行离散采样, 您必须设置样本列表(或范围)及其概率。 我正在使用 https://github.com/jacobmenick/sampling离散采样代码。 概率是通过 Paretto 分布计算的。只需从链接中复制代码并将其放在下面的代码片段之上即可运行。
节点 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);
关于javascript - 如何从 JavaScript 的 Math.random 生成包含边界的 Pareto 随机整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960704/