Skander J.
Skander J.

Reputation: 33

Extracting the coefficients of a polynomial from a lambda in Python

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.)

Upvotes: 2

Views: 2321

Answers (1)

Skander J.
Skander J.

Reputation: 33

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]

Upvotes: 1

Related Questions