Skip to content

Instantly share code, notes, and snippets.

@MartinThoma
Created July 2, 2012 19:56
Show Gist options
  • Save MartinThoma/3035321 to your computer and use it in GitHub Desktop.
Save MartinThoma/3035321 to your computer and use it in GitHub Desktop.
Cholesky-Zerlegung in Wikipedia oldid=104368978
#!/usr/bin/python
# -*- coding: utf-8 -*-
def choleskyDecomposition(A):
"""
@param A: a nested list which represents a symmetric,
positiv definit n x n matrix.
@return: False if it didn't work, otherwise the matrix G
"""
n = len(A)
# Initialisation of G with A
G = []
for i in xrange(n):
line = []
for j in xrange(n):
line.append(float(A[i][j]))
G.append(line)
# Computation of G
for i in xrange(0,n):
for j in xrange(0, i):
sum = G[i][j]
for k in xrange(0, j-1):
sum -= G[i][k] * G[j][k]
G[j][i] = sum / G[j][j]
sum = G[i][i]
for k in xrange(0, i):
sum -= G[k][i]**2
if sum > 0:
G[i][i] = sum**0.5
else:
return False
return G
print choleskyDecomposition([[1,2],[2,1]]) # Nicht positiv definit
print choleskyDecomposition([[5,2],[1,1]]) # not Hermitian
print choleskyDecomposition([[5,2],[2,1]]) # should be [[sqrt(5), 2/sqrt(5)],[0, 1/sqrt(5)]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment