python计算坐标点欧式距离_计算Python Numpy向量之间的欧氏距离实例

计算Python Numpy向量之间的欧氏距离,已知vec1和vec2是两个Numpy向量,欧氏距离计算如下:

import numpy

dist = numpy.sqrt(numpy.sum(numpy.square(vec1 - vec2)))

或者直接:dist = numpy.linalg.norm(vec1 - vec2)

# 补充知识:Python中计算两个数据点之间的欧式距离,一个点到数据集中其他点的距离之和

# 如下所示:

# 计算数两个数据点之间的欧式距离

import numpy as np

def ed(m, n):

    return np.sqrt(np.sum((m - n) ** 2))

i = np.array([1, 1])

j = np.array([3, 3])

distance = ed(i, j)

print(distance)

# 计算一个点到数据集中其他点的距离之和

from scipy import *

import pylab as pl

all_points = rand(500, 2)

pl.plot(all_points[:, 0], all_points[:, 1], 'b.')

pl.show()

from scipy import *

import pylab as pl

all_points = rand(500, 2)

pl.plot(all_points[:, 0], all_points[:, 1], 'b.')

pl.show()

# 定义函数计算距离
#指定点,all_points:为集合类的所有点
def cost(c, all_points): 
    return sum(sum((c - all_points) ** 2, axis=1) ** 0.5)

Guess you like

Origin blog.csdn.net/l641208111/article/details/121548074