Homogeneous Coordinates and the Perspective Divide

3D GeometryMedium+20 XP+15

Homogeneous Coordinates and the Perspective Divide

A 3×3 matrix can rotate and scale a point, but it can't move one — every linear map pins the origin in place. Adding a fourth coordinate fixes that: write the point as [x, y, z, 1] and translation becomes just another matrix multiply.

Task: write apply_transform(matrix, points) where matrix is 4×4 and points is a list of [x, y, z]. Return the transformed points as [x, y, z], rounded to 4 decimal places.

  • Extend each point to [x, y, z, 1] before multiplying.
  • Afterwards, divide all four components by w (the fourth), then drop it. If w is 0, leave the components as they are.
  • An empty list of points returns an empty list.

That divide is the whole reason perspective projection works. An affine transform always leaves w = 1 and the division does nothing — but a projection matrix sets w proportional to depth, so the same line of code is what makes distant things smaller.

Examples

matrix = [[1.0, 0.0, 0.0, 2.0], [0.0, 1.0, 0.0, 3.0], [0.0, 0.0, 1.0, 4.0], [0.0, 0.0, 0.0, 1.0]]
points = [[1.0, 1.0, 1.0]]
returns [[3.0, 4.0, 5.0]]
matrix = [[0.0, -1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
points = [[1.0, 0.0, 5.0], [0.0, 2.0, 0.0]]
returns [[0.0, 1.0, 5.0], [-2.0, 0.0, 0.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run