find_root of function involving maximal eigenvalue
I have defined a function returning the leading eigenvalue of a matrix L as follows (the first function is to handle what I think are numerical errors, where what should be a real eigenvalue is seen as x + 0.?e-80*I, for instance):
def is_essentially_real(x):
if x.imag() == 0:
return(True)
else:
return(False)
def get_leading_eigenvalue(L):
evals = L.eigenvalues()
moduli = [e.n() for e in evals if is_essentially_real(e)]
moduli = [e for e in moduli if e >= 0]
r = max(moduli)
return(r)
I want to solve equations involving this function using find_root. As a toy example, I have the following:
def mat(b):
M = matrix(RR, 2, 2, [1, b, 1, 2])
return(M)
def f(b):
M = mat(b)
r = get_leading_eigenvalue(M)
return(r)
b = var(b)
find_root(f(b) - 3, 1,3 ) #produces error
I know that f(2) = 3, so if I understand correctly, my last line of code should return the number 2. Instead, I get the following message:
TypeError: Cannot evaluate symbolic expression to a numeric value.
My best guess is that the method matrix.eigenvalues() does not play well with the method find_roots(), but I am not sure how to get around this. I have tried changing the matrix field to both of QQ and SR, to no avail. Any feedback is appreciated. Also, this is my first question on the site, so if I've committed any sins, please let me know.