I'm creating an Android app and I need to calculate the movement speed of the device. I do this by taking an average of some earlier locations' speeds.
However, I need the speed to be in km/h
as an int
, so I use
(int)Math.ceil(speedAsDouble)
However, this always equal to 1
, even if the speedAsDouble
is 7.8825246
or 0.58178
.
This is the relevant part of the code:
// Create a variable for the speed
double speedAsDouble = 0d;
// Loop through the last points
for(int i = 0; i < lastPoints.size() - 1; i++)
{
// Add the speed for the current point to the total speed
speedAsDouble += (double)(lastPoints.get(i).distanceTo(lastPoints.get(i + 1)) / (lastPoints.get(i + 1).getTime() - lastPoints.get(i).getTime()));
}
// Divide the speed by the number of points
speedAsDouble /= (double)lastPoints.size();
// Convert the speed to km/h
speedAsDouble *= 3.6d;
// Log the speed
System.out.println("Speed: " + speedAsDouble);
I then round the number and cast it to an int as described above using
int speedAsInt = (int)Math.ceil(speedAsDouble)
and log the number again with
System.out.println("Rounded speed: " + speedAsInt)
Here is a part of the log:
05-17 12:00:42.605 24610-24610/package I/System.out﹕ Speed: 0.0
05-17 12:00:42.635 24610-24610/package I/System.out﹕ Rounded speed: 0
05-17 12:00:43.625 24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4
05-17 12:00:43.645 24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:44.595 24610-24610/package I/System.out﹕ Speed: 5.27003884781152E-4
05-17 12:00:44.615 24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:45.595 24610-24610/package I/System.out﹕ Speed: 4.216031078249216E-4
05-17 12:00:45.635 24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:46.595 24610-24610/package I/System.out﹕ Speed: 0.002668234216980636
05-17 12:00:46.605 24610-24610/package I/System.out﹕ Rounded speed: 1
I've spent much time looking at this, trying different variable types and casting variables but with no success.
In all the outputs you printed (except the first one which is 0) Speed
is smaller than 1 ( 7.026718463748694E-4
, 5.27003884781152E-4
, etc...). Notice the negative exponent.
Therefore it's no wonder ceil
returns 1.
Please look more carefully at your output, for example:
05-17 12:00:43.625 24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4
doesn't mean you have 7.02, but 0.000702. There is E-4
at the end. When you would use ceil it will always return 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.