Simple maths for GPS (Haversine) math.h had appeared very inaccurate LPC1768 (fixed)
Below are three test cases with results in metres for the pairs of Delta geographic coords.
The results shown in brackets match both with Excel and Google Maps.
However, using the math.h library anything below 1000m is very inaccurate
Obviously as the distance goes up the inaccuracy get swamped.
I have checked that 'treat doubles as floats' is not set.
Why are my results so inaccurate please?
Mark
double test_distance()
{
//42.78724667 147.246516667 to 42.7872449999 147.2465333 (1.36m) 30m with math.h
// 42.7872466666, 147.247016667, 42.7872449999, 147.247742 (100m) 60m with math.h
// 42.7872466666, 147.247016667, 42.7872449999, 147.25877 (1000m) 990m with math.h
double result = haversine(42.7872466666, 147.247016667, 42.7872449999, 147.247742);
}
#define M_PI (double)3.14159265358979
double haversine(double lat1, double lon1, double lat2, double lon2)
{
// Convert degrees to radians
lat1 = lat1 * M_PI / (double)180.0;
lon1 = lon1 * M_PI / (double)180.0;
lat2 = lat2 * M_PI / (double)180.0;
lon2 = lon2 * M_PI / (double)180.0;
// P
double dlat = lat2lat1;
double dlon = lon2lon1;
double sumlat = lat1 + lat2;
double calc = dlon * cos(sumlat/(double)2.0);
calc *=calc;
dlat *=dlat;
double distance = sqrt(calc + dlat) * (double)6371000.0;
return distance;
}

Hi Michael here is a better example with the problem
#include "processing.h"
#include <math.h>
#include <stdio.h>double haversine(double lat1, double lon1, double lat2, double lon2);
double test_distance()
{
//42.78724667 147.246516667 to 42.7872449999 147.2465333 (1.36m)
// 42.7872466666, 147.247016667, 42.7872449999, 147.247742 (100m)
// 42.7872466666, 147.247016667, 42.7872449999, 147.25877 (1000m)
double result = haversine(42.7872466666, 147.247016667, 42.7872449999, 147.247742);
}#define M_PI (double)3.14159265358979
double haversine(double lat1, double lon1, double lat2, double lon2)
{
// Convert degrees to radians
lat1 = lat1 * M_PI / (double)180.0;
lon1 = lon1 * M_PI / (double)180.0;
lat2 = lat2 * M_PI / (double)180.0;
lon2 = lon2 * M_PI / (double)180.0;
// P
double dlat = lat2lat1;
double dlon = lon2lon1;
double sumlat = lat1 + lat2;
double calc = dlon * cos(sumlat/(double)2.0);
calc *=calc;
dlat *=dlat;double distance = sqrt(calc + dlat) * (double)6371000.0;
return distance;
} 
Yes the result should yield 1.3m but I'm getting 59 in firmware and 1.3 in excel and google maps.
It seems I have to resign to the fact that math.h in both MS and GCC doesn't have the accuracy for gps. I am wondering if there are other libraries out there that can deal with long doubles math.
Thanks for you help
Please sign in to leave a comment.
Comments
12 comments