javascript - 如何从 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)
解决方案
好的,首先你的代码中有一个错误,你不能包含 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);
推荐阅读
- vuejs2 - 尽管 URL 已更改,但无法加载组件
- realex-payments-api - iOS 和 Android 上的 3DS2:HPP 还是 API?
- java - 为第三方 jar 应用设置深色背景
- java - 如何从 Cloud FireStore 获取图像数组列表到 imageslider
- django - 为什么在 django 迁移时出现未定义的错误?
- laravel - Laravel 7 和 Babel
- xamarin.android - Xamarin- 为所有 Android 版本重建?
- amazon-web-services - 如何使用 AWS Batch 提高计算速度
- vue.js - Vue DevTools beta 未出现在 Brave Browser 开发者工具中
- java - 如何解决错误“委托被拒绝
” 当我调用 Gmail API 时,它在 JAVA 中返回 403 错误代码