[简介这些经纬线是怎样定出来的呢?地球是在不停地绕地轴旋转(地轴是一根通过地球南北两极和地球中心的假想线),在地球中腰画一个与地轴垂直的大圆圈,使圈上的每一点都
#coding: utf-8
#封装函数
import math
def cal_dis(latitude1, longitude1,latitude2, longitude2):
latitude1 = (Math.PI/180)*latitude1
latitude2 = (Math.PI/180)*latitude2
longitude1 = (Math.PI/180)*longitude1
longitude2= (Math.PI/180)*longitude2
#因此AB两点的球面距离为:{arccos[sinb*siny+cosb*cosy*cos(a-x)]}*R
#地球半径
global R = 6378.1;
d = math.acos(math.sin(latitude1)*math.sin(latitude2)+\
math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1))*R
return d;
}
实现了根据输入两点经纬度,计算这两点距离的函数,但是在实际操作过程中,出现了报错:
ValueError: math domain error
下面是测试数据,这部分是正确的数据
print cal_dis(39.762146, -104.98248,39.758066, -104.902431)
print cal_dis(39.77455175, -105.01426466666665,39.76241472, -104.90343176000002)
print "横向一个纬度的距离:",cal_dis(39, -104,40, -104)
print "纵向一个经度的距离:",cal_dis(39, -105,39, -104)
print cal_dis(39.772779500000006, -104,39.762146, -104)下面是会报错的数据集:
print "error"
print cal_dis(-6.174444, 106.829444, -6.174444, 106.82944400000001)
print cal_dis(59.439339, 24.74682, 59.439339, 24.74682)
print cal_dis(59.439339, 24.74682, 59.439339, 24.74682)
print cal_dis(59.439339, 24.74682, 59.439339, 24.74682)
print cal_dis(37.647464, -77.624973, 37.647464, -77.624973)经过搜索相关文章,最终发现是由于acos(x)中的x越界引起的。
语法
以下是acos()方法的语法:
? 1
acos(x)
注意:此函数是无法直接访问的,所以我们需要导入math模块,然后需要用math的静态对象来调用这个函数。
参数
x -- 这必须是在范围内的数字值-1到1,如果x大于1,则它会产生一个错误。
返回值
此方法返回的X反余弦,以弧度表示。[ double hypot(double x, double y) ...{ return sqrt(x * x + y * y);}double distance(double wd1, double jd1, double wd2, double jd2) ...{// 根据经纬度坐标
解决方案:
查看越界代码,使用repr将数字转化为字符串显示、查看
temp = math.sin(latitude1)*math.sin(latitude2)+\
math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1)
temp=math.sin(latitude1)*math.sin(latitude2)+\
math.cos(latitude1)*math.cos(latitude2)*\
math.cos(longitude2-longitude1)
print temp,repr(temp)
发现打印结果是:1.0 1.0000000000000002
也就是实际的acos()函数的自变量是1.0000000000000002, 已经超出1的范围,由于精度问题只显示了1.0。
if temp>1.0:
print format(temp,".19e")
可看出在科学计数法下的输出 >>1.0000000000000002220e+00
推导公式本身出问题的机率很小,但计算机中的浮点数舍入误差会放大、缩小数据,从而溢出。因此代码改为:
#coding: utf-8
#封装函数
import math
def cal_dis(latitude1, longitude1,latitude2, longitude2):
latitude1 = (math.pi/180.0)*latitude1
latitude2 = (math.pi/180.0)*latitude2
longitude1 = (math.pi/180.0)*longitude1
longitude2= (math.pi/180.0)*longitude2
#因此AB两点的球面距离为:{arccos[sina*sinx+cosb*cosx*cos(b-y)]}*R (a,b,x,y)
#地球半径
R = 6378.1
temp=math.sin(latitude1)*math.sin(latitude2)+\
math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1)
if repr(temp)>1.0:
temp = 1.0
d = math.acos(temp)*R
return d;
[php 根据两点的经纬度计算距离]