Lesson 4 of 15

Magnitude: The Length of a Vector

Magnitude: The Length of a Vector

The magnitude (or length) of a vector is computed using the Pythagorean theorem extended to 3D:

|v| = √(x² + y² + z²)

In C++, use sqrt from <cmath>:

#include <cmath>

double magnitude(Tuple v) {
    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w);
}

The w component is included in the formula for completeness, though vectors always have w=0.

Examples

magnitude(vector(1, 0, 0)) = 1
magnitude(vector(0, 1, 0)) = 1
magnitude(vector(3, 4, 0)) = √(9 + 16) = √25 = 5
magnitude(vector(1, 2, 3)) = √14 ≈ 3.7417

The 3-4-5 right triangle is useful: vectors with components 3 and 4 in any two axes have magnitude 5.

Your Task

Implement magnitude(Tuple v) using sqrt.

Expected output:

1
5
JSCPP loading...
Loading...
Click "Run" to execute your code.