I am doing the following calculations in a loop:
https://jsfiddle.net/0xLvxjar/
var i = 0;
var times = 200;
var friction = 0.9925;
var velocity = 10;
var position = 100;
for (; i < times; i += 1) {
velocity *= friction;
position += velocity;
}
console.log(velocity) // 2.218723008169958
console.log(position) // 1129.722321918849
I would like to rewrite that as a Math function and eliminate the loop if possible.
Looking trough the JavaScript Math object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math I am not seeing something to handle this.
Is there a better way of getting to the final result using a Math formula?
Solve it with math:
// v_1 = v_0 * f
// p_1 = p_0 + v_1
//
// p_2 = p_1 + v_1 * f
// = p_0 + v_1 + v_1 * f
// = p_0 + v_0 * f + v_0 * f * f
// = p_0 + v_0 * (f + f^2)
At this point you might see that p_n = p_0 + v_0 * (f + f^2 + f^3 + ... + f^n)
.
From your formulary you might know that this is true:
Therefore p_n = p_0 + v_0 * f * (1 - f^n) / (1 - f)
.
Transferred to JavaScript you get this:
var n = 200;
var friction = 0.9925;
var velocity_0 = 10.0;
var position_0 = 100.0;
var velocity_n = velocity_0 * Math.pow(friction, n);
var position_n = position_0 + velocity_0 * friction * (1 - Math.pow(friction, n)) / (1 - friction);
alert(velocity_n);
alert(position_n);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments