【发布时间】:2021-08-24 04:46:15
【问题描述】:
我需要构建一个布尔概率测试,该测试可以定期运行并增加返回 true 的机会。
返回阳性测试的概率增加由变量 (nMax) 确定,该变量表示返回 true 概率为 95% 以上的组合结果的预期测试次数。
例如:对于 nMax = 1000
n = [1] has 'almost zero' percent chance of returning true
n = [2] has 'slightly more than almost zero' percent chance of returning true
....
n = [1000] still only has a 'small' chance of returning true but the combined result of n[1] -> n[1000] is now > .95
我曾多次尝试使用概率对数标度,但均未成功,但似乎没有一个特别有希望。非常欢迎您的想法。
function test(n, nMax){
let test = Math.random()
if (Math.random() > (1/(n/nMax))){
return true
} else {
return false
}
}
function runUntilTrue(){
let i = 1;
let result = false;
while (result == false){
result = test(i, 100)
i++
}
console.log(i + " tests until true was returned true")
}
runUntilTrue()
【问题讨论】:
-
请在minimal reproducible example 上分享您目前的进展情况。
-
添加了简单的框架 - 不拘泥于它
-
我认为这个问题在数学领域而不是在计算机科学领域......我想像
(n / (nMax - n)) * (n / nMax) * 0.95 > Math.random()这样的东西可能会起作用 -
使用
Math.random检查非常低的概率(如Math.random() < 0.000001)可能会出现问题。为什么不只调用一次Math.random来确定运行次数,而不是每次运行时调用它? -
trincot 的回答似乎符合您的要求。如果您想要一个通过
nth 调用(而不是 95% 的机会)返回 true 的函数,那么可能会这样做:const randomToN = (n, i = 1) => () => Math .random () < i++ / n然后myRandom(1000)是您的函数可以调用以取回布尔值。它将通过nth 调用返回true(然后永远返回。)
标签: javascript algorithm probability