user45623
user45623

Reputation: 621

Formula for calculating distance with decaying velocity

I have a moving graphic whose velocity decays geometrically every frame. I want to find the initial velocity that will make the graphic travel a desired distance in a given number of frames.

Using these variables:

I can come up with d = v * (r0 + r1 + r2 + ...)

So if I want to find the v to travel 200 pixels in 3 frames with a decay rate of 90%, I would adapt to:

d = 200

r = .9

v = d / (r0 + r1 + r2)

That doesn't translate well to code, since I have to edit the expression if the number of frames changes. The only solution I can think of is this (in no specific language):

r = .9
numFrames = 3
d = 200
sum = 1
for (i = 1; i < numFrames; i++) {
    sum = sum + power(r, i);
}
v = d / sum;

Is there a better way to do this without using a loop?

(I wouldn't be surprised if there is a mistake in there somewhere... today is just one of those days..)

Upvotes: 0

Views: 325

Answers (2)

Arjun Panickssery
Arjun Panickssery

Reputation: 183

What you have here is a geometric sequence. See the link: http://www.mathsisfun.com/algebra/sequences-sums-geometric.html

To find the sum of a geometric sequence, you use this formula:

sum = a * ((1 - r^n) / (1 - r))

Since you are looking for a, the initial velocity, move the terms around:

a = sum * ((1-r) / (1 - r^n))

In Java:

int distanceInPixels = SOME_INTEGER;
int decayRate = SOME_DECIMAl;
int numberOfFrames = SOME_INTEGER;

int initialVelocity; //this is what we need to find

initialVelocity = distanceinPixel * ((1-decayRate) / (1-Math.pow(decayRate, NumberOfFrames)));

Using this formula you can get any one of the four variables if you know the values of the other three. Enjoy!

Upvotes: 2

Stanton
Stanton

Reputation: 495

According to http://mikestoolbox.com/powersum.html, you should be able to reduce your for loop to:

F(x) = (x^n - 1)/(x-1)

Upvotes: 0

Related Questions