Lesson 5 of 15

Normalizing a Vector

Normalizing a Vector

A unit vector (or normalized vector) has a magnitude of 1. Normalizing converts any vector to a unit vector pointing in the same direction.

Tuple normalize(Tuple v) {
    double m = magnitude(v);
    return Tuple(v.x / m, v.y / m, v.z / m, v.w / m);
}

Why Normalize?

Many ray tracer computations require unit vectors — lighting calculations, ray directions, surface normals. Normalizing keeps geometry calculations consistent regardless of the original vector's length.

Examples

normalize(vector(4, 0, 0)) = vector(1, 0, 0)
normalize(vector(1, 2, 3)) ≈ vector(0.26726, 0.53452, 0.80178)

After normalizing, the magnitude of the result should always be 1.

Your Task

Implement normalize(Tuple v) using the magnitude function.

Expected output:

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