Reputation: 41
I have the following function defined:
def eigval(matrix):
a = matrix[0, 0]
b = matrix[0, 1]
c = matrix[1, 0]
d = matrix[1, 1]
c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
return c1 / 2, c2 / 2
It is created to find the eigenvalues of a 2 X 2 matrix. I am using it to iteratively run the Jacobi algorithm on a matrix. The matrix passed in is a dictionary that uses tuples as keys to represent the position and floats as values. This function will work fine for about 6 iterations, but then I will get a:
TypeError: __getitem__() takes exactly 2 arguments (2 given)
on the first line of the block (the one with the a).
I am completely confused by this because like I said, it works fine for about 6 runs and then stops.
EDIT: Here's a function that creates the kind of matrix I would pass in: (Given that the matrix will be different for each iteration)
def create():
matrix = {}
matrix[0, 0] = 2
matrix[0, 1] = 1
matrix[1, 0] = 1
matrix[1, 1] = 2
return matrix
Any help is greatly appreciated! (P.S. first post here)
Upvotes: 4
Views: 2107
Reputation: 609
Your matrix is a dict using tuples as keys, this is probably not what you want to do.
Try using nested lists:
from math import sqrt
def create():
matrix = [[1, 2], [1, 2]]
return matrix
def eigval(matrix):
a = matrix[0][0]
b = matrix[1][0]
c = matrix[0][1]
d = matrix[1][1]
c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
return [c1 / 2, c2 / 2]
>>> m = create()
>>> eigval(m)
[3.0, 0.0]
Or alternatively use numpy:
import numpy
def eigval(matrix):
a = matrix[0, 0]
b = matrix[1, 0]
c = matrix[0, 1]
d = matrix[1, 1]
c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
return numpy.array([c1 / 2, c2 / 2])
>>> m = numpy.array([[1, 2], [1, 2]])
>>> m
array([[1, 2],
[1, 2]])
>>> eigvalues, eigvectors = numpy.linalg.eig(m)
>>> eigvalues
array([ 0., 3.])
>>> eigval(m)
array([ 3., 0.])
Upvotes: 1