numpy.random.choice in Javascript?

梦想与她 提交于 2020-03-06 03:49:12

问题


Numpy.random.choice is a nice simple function, that lets you sample an array of ints based on some probability distribution:

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])

Is there an equivalent in javascript (node js)?

Note: I found this package https://www.npmjs.com/package/random-weighted-choice but I don't like creating a hashmap/table every time I need to get a sample.


回答1:


You could use this ES6 code:

function randomChoice(p) {
    let rnd = p.reduce( (a, b) => a + b ) * Math.random();
    return p.findIndex( a => (rnd -= a) < 0 );
}

function randomChoices(p, count) {
    return Array.from(Array(count), randomChoice.bind(null, p));
}

let result = randomChoices([0.1, 0, 0.3, 0.6, 0], 3);
console.log(result);

The reduce part calculates the sum of the probabilities. If it is expected that these always amount to 1, then of course that call is not necessary, and rnd = Math.random() would be enough.




回答2:


You could use lodash's _.sample function:

_.sample([1, 2, 3, 4]);
// => 2


来源:https://stackoverflow.com/questions/41654006/numpy-random-choice-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!