Matthijs Matthijs - 1 month ago 7x
Java Question

Average Speed Calculation returns 'infinity'

On my android google map application I'm trying to calculate the average speed by taking the time (in milliseconds) and distance (in meters) and performing the next calculation on it:

private double avgSpeed = 0;
public void calcAvgSpeed(double distance, long time) {
distance = distance / 1000; //1000 = km
time = time / 3600000; // 1000 = sec, 60000 = min, 3600000 = hrs
avgSpeed = (double) (distance / time);

to make sure it works i ran it with
calcAvgSpeed(300, 30000);
in which 300 is 300 meters and 30000 is 30000ms(or 30sec). Calculations I made say that avgSpeed should be 36 after the method. But when I print the result it says 'infinity' as if I'm dividing by zero..

Does anybody see if my method is wrong or why I get this weird answer?


You are indeeed dividing by zero.

time = time / 3600000;

performs an integer division since time is of type long.

To fix this use something like

avgSpeed = distance * 3600000 / time;