2

I'm working on some linear algebra and using numpy for reference. I use lambda k: numpy.linalg.det(A - k*I) to compute the characteristic polynomial of a matrix A.

That works wonderfully, and the next step would be to calculate the roots of that polynomial which represents the eigenvalues of the matrix, using numpy.roots, the problem being that numpy.roots takes a polynomial coefficients as argument.

Is there any way to extract the coefficients from the lambda k?

(I am aware of the existence of numpy.linalg.eigvals but I would rather not use it.)

Skander J.
  • 33
  • 7
  • its certainly possible to do it numerically. have a look at https://docs.scipy.org/doc/scipy/reference/optimize.html for an overview – L.Grozinger Nov 15 '20 at 21:22
  • Numpy and scipy provides eig and svd method. It would help you to determine eigenvalues. – jlandercy Nov 15 '20 at 21:29

1 Answers1

1

Found the answer thanks to How to find coefficients of polynomial equation?

# yields the coefficients from highest to lowest degree
def extract_coefficients(p, degree):
    n = degree + 1
    sample_x = [ x for x in range(n) ]
    sample_y = [ p(x) for x in sample_x ]
    A = [ [ 0 for _ in range(n) ] for _ in range(n) ]
    for line in range(n):   
        for column in range(n):
            A[line][column] = sample_x[line] ** column
    c = numpy.linalg.solve(A, sample_y)
    return c[::-1]

Running extract_coefficients(lambda x: 2*x**2 - 2*x + 1, 2) yields the correct result [ 2. -2. 1.]. Many thanks to the people who originally responded! Edit: The code can be compressed further if you don't care about readability as such:

# yields the coefficients from highest to lowest degree
def extract_coefficients(p, d):
    return (numpy.linalg.solve([[[x for x in range(d+1)][line] ** column for column in range(d+1)] for line in range(d+1)], [p(x) for x in [x for x in range(d+1)]]))[::-1]

Skander J.
  • 33
  • 7