0

I'm trying to create an unknown variable in numpy in order to calculate eigenvalues without using the built in functions. I want to create a matrix that looks like this for example

-x     1
-2  -3-x

But entering x into a matrix, it won't recognize what x is and I don't know how to define it properly. This is my code so far and it says that x is not defined.

x=x
A = np.array([[0,1-x],[-2,-3-x]])
B = np.array([[0,1],[-2,-3]])

print(B)

How do I define the variable x so that I can use it as an algebra function?

Reti43
  • 9,656
  • 3
  • 28
  • 44
effa94
  • 31
  • 5
  • 1
    From where does x come in your program? Are you taking it as user input, or as a function parameter? – Ganesh Tata May 09 '21 at 14:01
  • Does this answer your question? [Evaluate sympy expression from an array of values](https://stackoverflow.com/questions/10678843/evaluate-sympy-expression-from-an-array-of-values) – user4933 May 09 '21 at 14:19

1 Answers1

2

Numpy doesn't deal with symbolic maths, but sympy does.

import numpy as np
import sympy as sym

x = sym.symbols('x')
a = sym.Matrix([[0,1-x],[-2,-3-x]])
b = sym.Matrix([[0,1],[-2,-3]])

print(a.eigenvals(multiple=True))
print(b.eigenvals(multiple=True))
# If everything is numerical, you can convert it to a numpy array
b_num = np.array(b).astype(np.float64)
# According to the documentation they aren't necessarily in order
print(np.linalg.eigvals(b_num))

Output

[-x/2 - sqrt(x**2 + 14*x + 1)/2 - 3/2, -x/2 + sqrt(x**2 + 14*x + 1)/2 - 3/2]
[-2, -1]
[-1. -2.]
Reti43
  • 9,656
  • 3
  • 28
  • 44