gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Hello, I want to develop a Python code that is going to do gram-scmidt process for me…
- User
Hello, I want to develop a Python code that is going to do gram-scmidt process for me for creating orthonormal vectors from given vectors. Can you write the code?
- Assistant
Certainly! Below is a Python implementation of the Gram-Schmidt process that takes a list of vectors (each vector as a list or numpy array) and returns an orthonormal set of vectors.
import numpy as np def gram_schmidt_process(vectors): """ Perform Gram-Schmidt process on a list of vectors to produce an orthonormal basis. Parameters: vectors (list or array-like): List of input vectors (each vector is array-like). Returns: np.ndarray: Orthonormal vectors as columns in a 2D numpy array. """ vectors = [np.array(v, dtype=float) for v in vectors] orthonormal_basis = [] for v in vectors: # Subtract the projection of v onto each vector in orthonormal_basis for u in orthonormal_basis: proj = np.dot(u, v) * u v = v - proj # Normalize v if it's not zero vector norm = np.linalg.norm(v) if norm > 1e-10: orthonormal_basis.append(v / norm) else: # If vector is too close to zero, ignore it (dependent vector) pass return np.array(orthonormal_basis) # Example usage: vectors = [ [1, 1, 0], [1, 0, 1], [0, 1, 1] ] orthonormal_vectors = gram_schmidt_process(vectors) print("Orthonormal basis:") print(orthonormal_vectors)