EN
TypeScript - calculate distance between two points with Pythagorean equation
0
points
In this article, we would like to show you how to calculate the distance between two points with the Pythagorean equation using TypeScript.
Quick solution:
// P1 = (x1, y1); P2 = (x2, y2)
const a = x2 - x1;
const b = y2 - y1;
const distance = Math.sqrt(a * a + b * b);
Quick example:
// ONLINE-RUNNER:browser;
const a = 3 - 1;
const b = 3 - 1;
const distance = Math.sqrt(a * a + b * b);
console.log(distance); // 2.8284271247461903
1. Mathematical theorem on the coordinate system
Distance calculation for points requires starting with the transformation of the Pythagorean equation to the point version.
a^2 + b^2 = c^2 => c = sqrt(a^2 + b^2)
a = |x2 - x1|
b = |y2 - y1|
c = sqrt(|x2 - x1|^2 + |y2 - y1|^2)
what can be transformed to:
c = sqrt((x2 - x1)^2 + (y2 - y1)^2)
distance between P1 and P2 is equal to c
Note: absolute value of
a
andb
can be avoided because of squares inside Pythagorean equation - squares remove minuses.

Example calculations:
a = |x2 - x1| = |3 - 7| = 4
b = |y2 - y1| = |5 - 2| = 3
c = sqrt(4^2 + 3^2) = sqrt(16 + 9) = sqrt(25) = 5
2. TypeScript custom distance function example
const calculateDistance = (p1: Point, p2: Point): number => {
const a = p2.x - p1.x;
const b = p2.y - p1.y;
return Math.sqrt(a * a + b * b);
};
// Usage example:
interface Point {
x: number;
y: number;
}
const p1: Point = { x: 7, y: 2 };
const p2: Point = { x: 3, y: 5 };
const distance: number = calculateDistance(p1, p2);
console.log(distance); // 5
Output:
5
3. Math.hypot()
method example
Note:
Math.hypot()
has been introduced in ECMAScript 2015.
const calculateDistance = (p1: Point, p2: Point): number => {
const a = p2.x - p1.x;
const b = p2.y - p1.y;
return Math.hypot(a, b);
};
// Usage example:
interface Point {
x: number;
y: number;
}
const p1: Point = { x: 7, y: 2 };
const p2: Point = { x: 3, y: 5 };
const distance: number = calculateDistance(p1, p2);
console.log(distance); // 5
Output:
5