python函数——根据经纬度计算距离公式的错误及修正

来源:互联网 发布:mysql连不上localhost 编辑:程序博客网 时间:2024/05/19 08:25
#coding: utf-8#封装函数import mathdef cal_dis(latitude1, longitude1,latitude2, longitude2):latitude1 = (Math.PI/180)*latitude1latitude2 = (Math.PI/180)*latitude2longitude1 = (Math.PI/180)*longitude1longitude2= (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))*Rreturn 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反余弦,以弧度表示。

解决方案:

查看越界代码,使用repr将数字转化为字符串显示、查看

temp = math.sin(latitude1)*math.sin(latitude2)+\ math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1)
<pre name="code" class="python">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 mathdef cal_dis(latitude1, longitude1,latitude2, longitude2):latitude1 = (math.pi/180.0)*latitude1latitude2 = (math.pi/180.0)*latitude2longitude1 = (math.pi/180.0)*longitude1longitude2= (math.pi/180.0)*longitude2#因此AB两点的球面距离为:{arccos[sina*sinx+cosb*cosx*cos(b-y)]}*R  (a,b,x,y)#地球半径R = 6378.1temp=math.sin(latitude1)*math.sin(latitude2)+\ math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1)if repr(temp)>1.0: temp = 1.0d = math.acos(temp)*Rreturn d;

0 0
原创粉丝点击