Amsik
Amsik

Reputation: 728

Computing distance by time and speed in java

I have multiple records with speed (in KM/h) and time (in Date) and i would like to know what was total distance traveled. Time and speed is changing. Is there any java algorythm for this?

Upvotes: 0

Views: 1988

Answers (4)

Qwerky
Qwerky

Reputation: 18445

If you have data points of speed and time you need to work out the average speed between points (this may not be accurate, but its the best you can do with the data) and multiply by the time. Note that I have used seconds as the time measurement. You say you have Date, so you should be able to convert easily, probably best to use miliseconds if your times are close together.

Lets say you have the following data points;

Time speed
0    12
4    15
7    13
11   18
17   21

The average speed between point 1 and 2 is;

12 + 15 / 2 = 13.5

and the time difference is 4 seconds. The best calculation you can make is that the distance travelled between these data points is

4 * 13.5 * (1000 / 3600) = 15 metres

the (1000 / 3600) bit is converting km/h into m/s.

Your algorithm needs to perform the same calculation with each pair of data points and add up the total distance travelled.

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Essentially you need to plot the curve between the points (x axis = time, y axis = speed) and calculate the area under that graph. Obviously this will vary depending on your choice of interpolation (straight line, bezier curve, cubic spline etc.)

This looks like an interesting list of interpolation libraries.

There also seems to be a javax.media.jai.Interpolation component available.

Upvotes: 0

Laky
Laky

Reputation: 965

Simply calculate for each consequent pair of values this:

distance = previousVelocity * timeDifference + (currentVelocity - previousVelocity) * timeDifference / 2

Where timeDifference = currentTime - previousTime.

Then sum it all up and there you go. This is assuming constant acceleration and deceleration.

Upvotes: 1

poitroae
poitroae

Reputation: 21367

There is no predefined "Java algorithm" for this. You have to calculate the entire distance by adding up all ds = v * dt. ds is delta distance, v is the velocity and dt delta time. A loop will do fine. Other than that, you could determine the average speed and do one multiplication.

Upvotes: 0

Related Questions