在接近零之前,我可以将一个数字乘以 decimal/fraction 多少次

How many times can I multiple a number by a decimal/fraction before it reaches close to zero

我正在尝试根据物体的速度来确定检查壁架的距离。这样物体就可以停止加速,让摩擦停止。

问题

每一步摩擦力为 0.9 * horizo​​ntalSpeed。

当 horizo​​ntalSpeed 小于 0.001 时,我们将 horizo​​ntalSpeed 设置为 0

达到 0.001 需要多长时间 horizo​​ntalSpeed = 1

我目前如何解决

var horizontalSpeed = 1    
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = 0

while(horizontalSpeed > closeEnoughToZero) {
    horizontalSpeed *= friction
    distance += horizontalSpeed
}

console.log(distance) // 8.99

可能已经是解决方案了,我只是觉得它有点蛮力,可能是某种类型的数学函数对此很方便!

这是一个 "pure maths" 解决方案

var horizontalSpeed = 1    
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = (horizontalSpeed * friction)/(1-friction)

console.log(distance)

或者,给定一个 "close enough to zero",这也可以在没有循环的情况下完成

var horizontalSpeed = 1    
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = 0

// this is the power you need to raise "friction" to, to get closeEnoughToZero
let n = Math.ceil(Math.log(closeEnoughToZero)/Math.log(friction)); 
// now use the formula for Sum of the first n terms of a geometric series
let totalDistance = horizontalSpeed * friction * (1 - Math.pow(friction, n))/(1-friction);
console.log(totalDistance);

我使用 Math.log(closeEnoughToZero)/Math.log(friction)Math.ceil - 在你的例子中是 66。如果你在代码中添加了一个循环计数器,你会看到循环执行了 66 次

并且,如您所见,第二个代码产生与循环完全相同的输出。