Euclidean Distance Between Two Points In C++
In this tutorial, we will consider two points P and Q on a 2D plane and compute and print the Euclidean Distance between them. We will also make sure that our absolute or relative error with the exact distance does not exceed 10 - 6.
Namely: Let’s assume that our answer is a, and the exact distance is b. Our implementation will ensure that, .
Calculation
We will find the Euclidean distance between two points using the Pythagoras Theorem approach. The Euclidean distance between any two points is
Implementation
Let’s do an implementation for the following example, where P(3, 4) and Q(5, 9) are the 2 points on XY plane. And let’s find the Euclidean Distance between them. We will be using the inbuilt library in GNU C++ 20. Below is the C++ implementation for the same.
#include"bits/stdc++.h" // Includes all inbuilt-library in GNU C++ compiler using namespace std; #define int long long // To prevent integer overflow double EuclideanDistance(double x1, double y1, double x2, double y2){ double x = x1-x2; double y = y1-y2; double dist = sqrtl(pow(x,2) + pow(y,2)); // Euclidean distance derived from Pythagoras Theorem return dist; } signed main(){ double x1 = 3; // x coordinate of first point P double y1 = 4; // y coordinate of first point P double x2 = 5; // x coordinate of second point Q double y2 = 9; // x coordinate of second point Q double dist = EuclideanDistance(x1, y1, x2, y2); cout<<"The Euclidean distance between the points P("<<x1<<", "<<y1<<") and Q("<<x2<<", "<<y2<<") is "; cout<<fixed<<setprecision(10)<<dist<<endl; // To set the floating points accuracy }
Output
The Euclidean distance between the points P(3, 4) and Q(5, 9) is 5.3851648071
Time Complexity
O(1)
Space Complexity
O(1)
Leave a Reply