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:
xxxxxxxxxx
1
// P1 = (x1, y1); P2 = (x2, y2)
2
const a = x2 - x1;
3
const b = y2 - y1;
4
const distance = Math.sqrt(a * a + b * b);
Quick example:
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
const a = 3 - 1;
4
const b = 3 - 1;
5
const distance = Math.sqrt(a * a + b * b);
6
7
console.log(distance); // 2.8284271247461903
Distance calculation for points requires starting with the transformation of the Pythagorean equation to the point version.
xxxxxxxxxx
1
a^2 + b^2 = c^2 => c = sqrt(a^2 + b^2)
2
3
a = |x2 - x1|
4
5
b = |y2 - y1|
6
7
c = sqrt(|x2 - x1|^2 + |y2 - y1|^2)
what can be transformed to:
xxxxxxxxxx
1
c = sqrt((x2 - x1)^2 + (y2 - y1)^2)
2
3
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:
xxxxxxxxxx
1
a = |x2 - x1| = |3 - 7| = 4
2
3
b = |y2 - y1| = |5 - 2| = 3
4
5
c = sqrt(4^2 + 3^2) = sqrt(16 + 9) = sqrt(25) = 5
xxxxxxxxxx
1
const calculateDistance = (p1: Point, p2: Point): number => {
2
const a = p2.x - p1.x;
3
const b = p2.y - p1.y;
4
5
return Math.sqrt(a * a + b * b);
6
};
7
8
// Usage example:
9
10
interface Point {
11
x: number;
12
y: number;
13
}
14
15
const p1: Point = { x: 7, y: 2 };
16
const p2: Point = { x: 3, y: 5 };
17
18
const distance: number = calculateDistance(p1, p2);
19
20
console.log(distance); // 5
Output:
xxxxxxxxxx
1
5
Note:
Math.hypot()
has been introduced in ECMAScript 2015.
xxxxxxxxxx
1
const calculateDistance = (p1: Point, p2: Point): number => {
2
const a = p2.x - p1.x;
3
const b = p2.y - p1.y;
4
5
return Math.hypot(a, b);
6
};
7
8
// Usage example:
9
10
interface Point {
11
x: number;
12
y: number;
13
}
14
15
const p1: Point = { x: 7, y: 2 };
16
const p2: Point = { x: 3, y: 5 };
17
18
const distance: number = calculateDistance(p1, p2);
19
20
console.log(distance); // 5
Output:
xxxxxxxxxx
1
5