Search code examples
javascriptunity-game-enginemathgame-enginegame-physics

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


I'm trying to determine how far ahead to check for a ledge based on an objects speed. This way the object can stop accelerating and let friction stop it.

enter image description here

the problem

friction is 0.9 * horizontalSpeed each step.

when horizontalSpeed is less than 0.001 we set the horizontalSpeed to 0

how long it takes to reach 0.001 is horizontalSpeed = 1

how im currently solving

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

Possible already the solution I just feel it is a bit brute force and likely some type of math function that is handy for this!


Solution

  • Here's a "pure maths" solution

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

    Or, given a "close enough to zero", that can be done without a loop too

    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);

    I use the Math.ceil of Math.log(closeEnoughToZero)/Math.log(friction) - which in your case is 66. If you added a loop counter to your code, you'd see the loop executes 66 times

    And, as you can see the second code produces exactly the same output as your loop.