Skip to content

Instantly share code, notes, and snippets.

@danilobellini
Created February 24, 2013 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilobellini/5022087 to your computer and use it in GitHub Desktop.
Save danilobellini/5022087 to your computer and use it in GitHub Desktop.
Gram-Schmidt orthonormalization with itertools.
# -*- coding: utf-8 -*-
# Gram-Schmidt orthonormalization with itertools.
# Copyright (C) 2012 Danilo de Jesus da Silva Bellini
#
# This is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Created on Fri Feb 22 04:36:17 2013
# danilo [dot] bellini [at] gmail [dot] com
"""
Gram-Schmidt orthonormalization with itertools.
"""
import itertools as it
def gram_schmidt(vects):
"""
Apply the Gram-Schmidt orthonormalization procedure to the given list of
lists (or a NumPy 2D array).
"""
result = []
for vect in vects:
coeffs = [sum(d * r for d, r in it.izip(vect, res)) for res in result]
data = [d - sum(r * c for r, c in it.izip(rs, coeffs))
for rs, d in it.izip_longest(it.izip(*result),
vect,
fillvalue=[])]
sqrt_norm = sum(abs(d) ** 2 for d in data) ** .5
result.append([d/sqrt_norm for d in data])
return result
if __name__ == "__main__":
# The example given in the material
data = gram_schmidt([[.866, .5, 0.],
[0., .5, .866],
[.7071, 0., .7071]])
# Below is just a nice way of printing the matrix
for row in data:
for el in row:
print "{0:>10f}".format(el),
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment