Lesson 3 of 18

Vector Magnitude

Vector Magnitude in 3D

The magnitude (or length) of a vector v=(x,y,z)\mathbf{v} = (x, y, z) is:

v=x2+y2+z2|\mathbf{v}| = \sqrt{x^2 + y^2 + z^2}

This is a direct extension of the Pythagorean theorem into three dimensions.

Unit Vectors

A vector with magnitude 1 is called a unit vector. To normalize any vector:

v^=vv=(xv,  yv,  zv)\hat{\mathbf{v}} = \frac{\mathbf{v}}{|\mathbf{v}|} = \left(\frac{x}{|\mathbf{v}|},\; \frac{y}{|\mathbf{v}|},\; \frac{z}{|\mathbf{v}|}\right)

Unit vectors indicate direction only.

Distance Between Points

The distance between P1=(x1,y1,z1)P_1 = (x_1, y_1, z_1) and P2=(x2,y2,z2)P_2 = (x_2, y_2, z_2) is the magnitude of their difference:

d=(x2x1)2+(y2y1)2+(z2z1)2d = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2 + (z_2-z_1)^2}

Examples

VectorMagnitude
(3, 4, 0)5
(1, 1, 1)31.7321\sqrt{3} \approx 1.7321
(2, 2, 1)3
(0, 0, 0)0

Your Task

Implement double vec_length3(double x, double y, double z) that returns the 3D vector magnitude.

Use #include <math.h> and the sqrt function.

TCC compiler loading...
Loading...
Click "Run" to execute your code.