开发者

Latitude/longitude vector to distance, strange problem with output

I have this code to find the distance between two sets of GPS coordinates, I got the code from elsewhere on the net.

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 

  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

The ouput returned looks like this: 25.44049 but if I do

$distance_output = distance(-50.12345, 100.1235,-60.12345,120.12345,'km');
echo $distance_output . '<br />;
echo $distance_output - 15.12345;

it outputs like this:

15.12345 
1.23639038e10

These are ju开发者_开发百科st made up numbers, but you can see the output of distance() looks like a number but then when I subtract the same number from it, it spits out a wierd exponential number. Any ideas?

Thanks a lot


Why is PHP printing my number in scientific notation, when I specified it as .000021?

Use number_format()


I tried your code (you just missed a simple quote), and the output is 1042.1216629565 and 1026.9982129565, seems ok to me.

If I substract 1042.1216629565 to 1042.1216629565, the output becomes 3.092281986028E-11 : note the minus character after the e.

This number is equal to 0.00000000003092281986028, not zero. This difference is common with floating point computation. It can be explained by rounding errors in value binary coding.

See wikipedia : http://en.wikipedia.org/wiki/Floating_point and particularly section about rounding.

If you want to display the result, use number_format()

If you want to compare two floating point values, you'll have to do use something like that :

 $epsilon = 1e-6;
 if (abs($value1-$value2) <= $epsilon){
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜