Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
How to Calculate the determinant of a matrix using NumPy?
Next article icon

Calculate the Euclidean distance using NumPy

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Euclidean distance is the shortest between the 2 points irrespective of the dimensions. In this article to find the Euclidean distance, we will use the NumPy library. This library used for manipulating multidimensional array in a very efficient way. Let’s discuss a few ways to find Euclidean distance by NumPy library.

Using np.linalg.norm()

np.linalg.norm() function computes the norm (or magnitude) of a vector, which in the case of the difference between two points, gives us the Euclidean distance. It’s a simple and efficient way to find the distance.

Python
import numpy as np  p1 = np.array((1, 2, 3)) p2 = np.array((1, 1, 1))  d = np.linalg.norm(p1 - p2) print(d) 

Output
2.23606797749979 

Explanation: We subtract p2 from p1 to get the difference vector (0, 1, 2). Then, np.linalg.norm(p1 – p2) directly calculates the Euclidean distance by finding the magnitude of the difference vector.

Using **

Here, we’re manually calculating the Euclidean distance by summing the squares of the differences between corresponding coordinates and then taking the square root of that sum. It’s a more “hands-on” approach compared to np.linalg.norm() but is functionally identical.

Python
import numpy as np  p1 = np.array((1, 2, 3)) p2 = np.array((1, 1, 1))  d = np.sqrt(np.sum((p1 - p2)**2)) print(d) 

Output
2.23606797749979 

Explanation: (p1 – p2)**2 squares each element of the difference vector. np.sum() adds up these squared values (0 + 1 + 4 = 5).

Using np.einsum()

np.einsum() function compute the dot product of the difference vector with itself, effectively squaring and summing the differences. While efficient for complex calculations, it may be overkill for simple distance computation.

Python
import numpy as np  p1 = np.array((1, 2, 3)) p2 = np.array((1, 1, 1))  d = np.sqrt(np.einsum('i,i->', p1 - p2, p1 - p2)) print(d) 

Output
2.23606797749979 

Explanation: First, we subtract p2 from p1 to get the difference vector (0, 1, 2). Then, np.einsum(‘i,i->’, p1 – p2, p1 – p2) calculates the dot product of this vector with itself, summing the squared differences (0 + 1 + 4 = 5).

Using np.dot()

np.dot() function computes the dot product of the difference vector with itself, effectively summing the squared differences. Applying np.sqrt() then gives the Euclidean distance between the two points.

Python
import numpy as np  p1 = np.array((1, 2, 3)) p2 = np.array((1, 1, 1))  d = np.sqrt(np.dot(p1 - p2, p1 - p2)) print(d) 

Output
2.23606797749979 

Explanation: This code calculates the difference vector (0, 1, 2) and then uses np.dot() to compute the sum of squared differences. Finally, np.sqrt() is applied to this sum.



Next Article
How to Calculate the determinant of a matrix using NumPy?
author
dadimadhav
Improve
Article Tags :
  • Python
  • Python numpy-Linear Algebra
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • Calculate Euclidean Distance Using Python OSMnx Distance Module
    Euclidean space is defined as the line segment length between two points. The distance can be calculated using the coordinate points and the Pythagoras theorem. In this article, we will see how to calculate Euclidean distances between Points Using the OSMnx distance module. Syntax of osmnx.distance.
    4 min read
  • Python | Calculate Distance between two places using Geopy
    GeoPy is a Python library that makes geographical calculations easier for the users. In this article, we will see how to calculate the distance between 2 points on the earth in two ways. How to Install GeoPy ? pip install geopy Geodesic Distance: It is the length of the shortest path between 2 point
    1 min read
  • How to Calculate the determinant of a matrix using NumPy?
    The determinant of a square matrix is a special number that helps determine whether the matrix is invertible and how it transforms space. It is widely used in linear algebra, geometry and solving equations. NumPy provides built-in functions to easily compute the determinant of a matrix, let's explor
    2 min read
  • Compute the condition number of a given matrix using NumPy
    In this article, we will use the cond() function of the NumPy package to calculate the condition number of a given matrix. cond() is a function of linear algebra module in NumPy package. Syntax: numpy.linalg.cond(x, p=None) Example 1: Condition Number of 2X2 matrix C/C++ Code # Importing library imp
    2 min read
  • Pandas - Compute the Euclidean distance between two series
    There are many distance metrics that are used in various Machine Learning Algorithms. One of them is Euclidean Distance. Euclidean distance is the most used distance metric and it is simply a straight line distance between two points. Euclidean distance between points is given by the formula : [Tex]
    2 min read
  • Python | Calculate City Block Distance
    City block distance is generally calculated between 2-coordinates of a paired object. It is the summation of absolute difference between 2-coordinates. The city block distance of 2-points a and b with k dimension is mathematically calculated using below formula: In this article two solution are expl
    2 min read
  • Absolute Deviation and Absolute Mean Deviation using NumPy | Python
    Absolute value: Absolute value or the modulus of a real number x is the non-negative value of x without regard to its sign. For example absolute value of 7 is 7 and the absolute value of -7 is also 7. Deviation: Deviation is a measure of the difference between the observed value of a variable and so
    3 min read
  • Calculate the sum of the diagonal elements of a NumPy array
    Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy.trace() and numpy.diagonal() method. Method 1: Finding the sum of diagonal elements using nump
    2 min read
  • Calculate Great Circle Distances Between Pairs of Points Using OSMnx Module
    The Great Circle Distance evaluates the shortest distance between two points considering Earth as a sphere. It is an arc linking two points on a sphere. Here, we will see how to calculate great circle distances between pairs of points using the OSMnx distance module. Syntax of osmnx.distance.great_c
    3 min read
  • Indexing Multi-dimensional arrays in Python using NumPy
    In this article, we will cover the Indexing of Multi-dimensional arrays in Python using NumPy. NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific compu
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences