EN
TypeScript - calculate distance between two points in 3D space
0 points
In this article, we would like to show you how to calculate the distance between two points in 3D space using a modified Pythagorean equation in TypeScript.
Quick solution:
xxxxxxxxxx
1
// P1 = (x1, y1, z1); P2 = (x2, y2, z2)
2
3
const a = x2 - x1;
4
const b = y2 - y1;
5
const c = z2 - z1;
6
7
const distance = Math.sqrt(a * a + b * b + c * c);
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 = d^2 => d = sqrt(a^2 + b^2 + c^2)
2
3
P1 = (x1, y1, z1); P2 = (x2, y2, z2)
4
5
a = |x2 - x1|
6
b = |y2 - y1|
7
c = |z2 - z1|
8
9
d = sqrt(|x2 - x1|^2 + |y2 - y1|^2 + |z2 - z1|^2)
what can be transformed to:
xxxxxxxxxx
1
d = sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2)
2
3
Distance between P1 and P2 is equal to d.
Note: absolute values can be avoided because of squares inside Pythagorean equation - squares remove minuses.
Example calculations:
xxxxxxxxxx
1
P1 = (7, 2, 3); P2 = (3, 5, 8)
2
3
a = |x2 - x1| = |3 - 7| = 4
4
b = |y2 - y1| = |5 - 2| = 3
5
c = |z2 - z1| = |8 - 3| = 5
6
7
d = sqrt(4^2 + 3^2 + 5^2) = sqrt(16 + 9 + 25) = sqrt(50)
8
d = 7.071067811865475
xxxxxxxxxx
1
const calculateDistance = (p1: Point, p2: Point): number => {
2
const a = p2.x - p1.x;
3
const b = p2.y - p1.y;
4
const c = p2.z - p1.z;
5
6
return Math.sqrt(a * a + b * b + c * c);
7
};
8
9
10
// Usage example:
11
12
interface Point {
13
x: number;
14
y: number;
15
z: number;
16
}
17
18
const p1: Point = { x: 7, y: 2, z: 3 };
19
const p2: Point = { x: 3, y: 5, z: 8 };
20
21
const distance: number = calculateDistance(p1, p2);
22
23
console.log(distance); // 7.0710678118654755
Output:
xxxxxxxxxx
1
7.0710678118654755
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
const c = p2.z - p1.z;
5
6
return Math.hypot(a, b, c);
7
};
8
9
10
// Usage example:
11
12
interface Point {
13
x: number;
14
y: number;
15
z: number;
16
}
17
18
const p1: Point = { x: 7, y: 2, z: 3 };
19
const p2: Point = { x: 3, y: 5, z: 8 };
20
21
const distance: number = calculateDistance(p1, p2);
22
23
console.log(distance); // 7.0710678118654755
Output:
xxxxxxxxxx
1
7.0710678118654755