如何使用 NumPy 计算欧几里得距离? [英] How can the Euclidean distance be calculated with NumPy?

查看:34
本文介绍了如何使用 NumPy 计算欧几里得距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 3D 中有两点:

(xa, ya, za)(xb, yb, zb)

我想计算距离:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

使用 NumPy 或一般的 Python 执行此操作的最佳方法是什么?我有:

导入numpya = numpy.array((xa,ya, za))b = numpy.array((xb, yb, zb))

解决方案

使用

I have two points in 3D:

(xa, ya, za)
(xb, yb, zb)

And I want to calculate the distance:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

What's the best way to do this with NumPy, or with Python in general? I have:

import numpy
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))

解决方案

Use numpy.linalg.norm:

dist = numpy.linalg.norm(a-b)

You can find the theory behind this in Introduction to Data Mining

This works because the Euclidean distance is the l2 norm, and the default value of the ord parameter in numpy.linalg.norm is 2.

这篇关于如何使用 NumPy 计算欧几里得距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆