Home >Backend Development >Python Tutorial >How Can NumPy Efficiently Calculate Euclidean Distance Between Two 3D Points?

How Can NumPy Efficiently Calculate Euclidean Distance Between Two 3D Points?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 14:22:14953browse

How Can NumPy Efficiently Calculate Euclidean Distance Between Two 3D Points?

Calculating Euclidean Distance with NumPy

In 3D space, given two points a = (ax, ay, az) and b = (bx, by, bz), the Euclidean distance between them is expressed as:

dist = sqrt((ax-bx)^2 (ay-by)^2 (az-bz)^2)

How can NumPy be employed to calculate this distance?

Using NumPy, you have arrays a and b representing the two points:

import numpy
a = numpy.array((ax, ay, az))
b = numpy.array((bx, by, bz))

Solution:

To solve this, leverage numpy.linalg.norm:

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

The default value of the ord parameter in numpy.linalg.norm is 2, corresponding to the l2 norm. As the Euclidean distance formula represents the l2 norm, this calculation accurately measures the distance between the points.

This functionality draws its theoretical foundation from Introduction to Data Mining, as illustrated below:

[Image of theoretical explanation from Introduction to Data Mining]

The above is the detailed content of How Can NumPy Efficiently Calculate Euclidean Distance Between Two 3D Points?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn