对于棋盘游戏的赔率计算器,我需要计算一场战斗平均会持续多少轮。因为战斗中的双方都有失手的可能,所以理论上一场战斗可以永远持续下去。因此我不能遍历所有分支,但需要计算一个数学极限。通过模拟器验证,我发现以下函数正确地近似了剩余的平均轮数:
// LIMIT could be any number, the larger it is, the more accurate the result.
const LIMIT = 100;
// r is the number of rounds left if at least 1 of the sides hit
// x is the chance that both sides miss and the round count gets increased,
// but the battle state stays the same.
function approximateLimitForNumberOfRounds(r: number, x: number) {
let approx = r / (1 - x);
// n -> infinity
for (let n = 1; n < LIMIT; n++) {
approx += x ** n;
}
return approx;
}
如何修改此函数以准确计算剩余的轮数,而不是近似它?(注意,因为x
是一个机会,所以它包含在(0, 1)
or中0 < x < 1
)。
我们可以注意到它approx
具有以下值:
r / (1 - x) # I refer to this as 'a' below
a + x
a + x + x^2
a + x + x^2 + x^3
a + x + x^2 + ... + x^n
因此,我们可以将数学表达式简化为:
a + (the sum of x^k from k = 1 to k = n)
接下来,我们必须注意,该序列x + x^2 + x^3 ...
形成了一个具有第一项x
和公比的几何序列x
。由于x
有界0 < x < 1
,这将有一个限制和,即:
x + x^2 + x^3 + ... x^inf = x/(1-x)
x = 1
(这显然在 时以及在采用的原始函数中失败r / (1 - x)
,但在这种情况下,您将简单地将总和设为无穷大,approx
如果不是,则将逃逸到无穷大undefined
;所以我假设x != 1
在以下计算中和x = 1
可以/已经单独处理)。
现在,由于我们既有一个用于x + x^2 + ...
无穷大的表达式,也有一个用于approx
包含的表达式,所以我们可以使用这两个事实x + x^2 + ...
来编写:approx
approx = r / (1 - x) + x / (1 - x)
approx = (r + x) / (1 - x)
你去吧!这是您在问题中概述的逻辑的数学等价物,压缩为单个语句(我认为这是正确的:))。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句