Compute an orthonormal basis for a set of 2D vectors using the Gram-Schmidt process. Given two linearly independent 2D vectors, produce two orthogonal unit vectors that span the same subspace.
import numpy as np
def gram_schmidt_2d(vectors: list[list[float]]) -> list[list[float]]:
result = []
for v in vectors:
v = np.array(v, dtype=float)
# Subtract projections onto all previous basis vectors
for u in result:
u = np.array(u)
v = v - np.dot(v, u) * u
# Normalize
norm = np.linalg.norm(v)
if norm < 1e-10:
continue # Skip linearly dependent vectors
v = v / norm
result.append(v.tolist())
return [list(map(lambda x: round(x, 4), v)) for v in result]v, subtract its projection onto each existing basis vector u: v = v - (v . u) * u. This makes v orthogonal to all previous vectors.