My code tracks an object that exists in virtual 3D space.
I have no direct access to the object's position, but it reports its coordinates, every so often. The exact frequency with which the updates occur is not exactly known or reliable, but I know it usually happens every X milliseconds.
Additionally, I cannot know when updates occur. Instead, the code is limited to a single function that runs many times a second (think ~60 times a second, but it should work reasonably well with more or less executions, too, and the rate can change during runtime). Every time the function runs, it has access to the object's last reported coordinates, as well as the exact current time (but not the time when the coordinates were reported).
The function must return its best estimate of what the object's current velocity and acceleration are.
The estimation is not trivial. For example, reading the exact same position twice in a row may mean the object stopped moving, or it may simply mean the moving object hasn't updated its position yet.
Here's a python/pseudocode example of a possible "solution," but not a very good one:
USUAL_UPDATE_RATE = X
STOPPING_THRESHOLD = USUAL_UPDATE_RATE * 1.2
lastTimePosition = None
lastVelocity = None
lastAcceleration = None
def update(time, position):
# First time running, can't estimate yet
if lastTimePosition is None:
lastTimePosition = (time, position)
return (0, 0)
lastTime, lastPosition = lastTimePosition
deltaTime = time - lastTime
# Ignore duplicate positions if not enough time has passed
if lastPosition == position and deltaTime < STOPPING_THRESHOLD:
return (lastVelocity, lastAcceleration)
# Calculate velocity
velocity = distance(position, lastPosition) / deltaTime
# If there's a previous velocity known, calculate acceleration
if lastVelocity is not None:
acceleration = (velocity - lastVelocity) / deltaTime
else:
acceleration = 0
# Save new values
lastTimePosition = (time, position)
lastVelocity = velocity
lastAcceleration = acceleration
return (velocity, acceleration)
The result is not good enough becuase the calculated velocity and acceleration values will vary wildly from call to call, even when the real velocity or acceleration haven't changed. I also tried averaging multiple velocities and accelerations together, but even then there is too much variation, and when averaging too many values, the results take too long to reflect the true values.
Given the limiting circumstances, what algorithm would give me the most accurate estimations, as close to real-time as possible?
Thanks in advance.