python numpy 求两点的距离 (推荐系统)

  • Post author:
  • Post category:python


求a,b两点的距离(二维):

import numpy as np
def eu_2(a,b):
    distance=np.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) #求两点的距离用两点横纵坐标的差值开根号
    return distance
eu_2([3,4],[8,1])

在三维坐标中求a,b两个点的距离:

import numpy as np
def eu_3(a,b):
    distance=np.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
    return distance
eu_3([3,4,1],[8,1,3])

求n维坐标中两点的距离:

import numpy as np
def eu_n(a,b):
    dis=0
    for i in range(len(a)):
        dis+=(a[i]-b[i])**2
    distance=np.sqrt(dis)
    return distance
eu_n([2,4,2,7],[6,4,2,8])



版权声明:本文为Luo_Ra原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。