javascript帮助中的概率?

jen*_*jen 8 javascript math

对不起,我是JS的新手,似乎无法解决这个问题:我怎么做概率?

我完全不知道,但我想做点什么:100%的几率,可能有0.7%的几率执行功能e();,30%的几率执行功能d();等等 - 他们将完全加起来100%每个的功能,但我还没有弄清楚如何以任何形式这样做.

我发现的主要是奇怪的高中数学教程"由Javascriptkit或其他东西驱动".

Rin*_*g Ø 16

例如,我们定义了许多功能

function a () { return 0; }
function b () { return 1; }
function c () { return 2; }

var probas = [ 20, 70, 10 ]; // 20%, 70% and 10%
var funcs = [ a, b, c ]; // the functions array
Run Code Online (Sandbox Code Playgroud)

该泛型函数适用于任意数量的函数,它执行它并返回结果:

function randexec()
{
  var ar = [];
  var i,sum = 0;


  // that following initialization loop could be done only once above that
  // randexec() function, we let it here for clarity

  for (i=0 ; i<probas.length-1 ; i++) // notice the '-1'
  {
    sum += (probas[i] / 100.0);
    ar[i] = sum;
  }


  // Then we get a random number and finds where it sits inside the probabilities 
  // defined earlier

  var r = Math.random(); // returns [0,1]

  for (i=0 ; i<ar.length && r>=ar[i] ; i++) ;

  // Finally execute the function and return its result

  return (funcs[i])();
}
Run Code Online (Sandbox Code Playgroud)

例如,让我们试试我们的3个函数,100000次尝试:

var count = [ 0, 0, 0 ];

for (var i=0 ; i<100000 ; i++)
{
  count[randexec()]++;
}

var s = '';
var f = [ "a", "b", "c" ];

for (var i=0 ; i<3 ; i++)
  s += (s ? ', ':'') + f[i] + ' = ' + count[i];

alert(s);
Run Code Online (Sandbox Code Playgroud)

我的Firefox上的结果

a = 20039, b = 70055, c = 9906
Run Code Online (Sandbox Code Playgroud)

所以一个运行约20%,b〜70%和C ^〜10%.


编辑以下评论.

如果你的浏览器有咳嗽return (funcs[i])();,只需更换funcs数组

var funcs = [ a, b, c ]; // the old functions array
Run Code Online (Sandbox Code Playgroud)

用这个新的(字符串)

var funcs = [ "a", "b", "c" ]; // the new functions array
Run Code Online (Sandbox Code Playgroud)

然后替换函数的最后一行 randexec()

return (funcs[i])(); // old
Run Code Online (Sandbox Code Playgroud)

用那个新的

return eval(funcs[i]+'()');
Run Code Online (Sandbox Code Playgroud)


And*_*per 6

像这样的事情应该有帮助:

var threshhold1 = 30.5;
var threshhold2 = 70.5;
var randomNumber = random() * 100;
if (randomNumber < threshhold1) {
   func1()
}
else if (randomNumber < threshhold2) {
   func2()
}
else {
   func3()
}
Run Code Online (Sandbox Code Playgroud)

执行func1()概率为 30.5%、func2()40% 和func3()29.5%。

您可能可以使用函数指针的阈值字典以及查找阈值大于的第一个字典条目的循环来更优雅地完成此操作randomNumber