Reputation: 61
Lets say I want an array vector like this one [x , 2x] and then I want to compute this array when x=5. So the result become [5 , 10].
This can be easily done in matlab using symbolic toolbox. However, I just moved from matlab to python and I was recommended to use Numpy and Sympy to replace Matlab powerful matrix manipulations.
I tried the following code
import numpy as np
import sympy as sp
x=sp.symbols('x')
a=np.array([x , 2*x])
However, I could not find any command that can be used to evaluate "a" when x is any number.
Can someone direct me to the correct path please.
Upvotes: 1
Views: 13426
Reputation: 231510
In [41]: from sympy import Matrix
In [42]: m = Matrix([x, 2*x])
In [43]: m.subs(x,23)
Out[43]:
⎡23⎤
⎢ ⎥
⎣46⎦
Upvotes: 2
Reputation: 80409
As explained by hpaulj in the comments, SymPy and NumPy live in separate worlds.
If you need fast number crunching, NumPy is your hero.
SymPy shines in symbolic manipulations.
To step from SymPy to NumPy, you either convert everything to numbers in SymPy before turning it over to NumPy. Or you use lambdify
which converts SymPy expressions to NumPy functions.
See e.g. this post how SymPy calculates derivatives of very complex expressions, which are then converted to NumPy functions.
If you really want speed, a library such as Numba can convert NumPy functions to machine code (without the need of external compilation steps).
These libraries are very powerful on their own, but lack fluent interoperability, which can be confusing in the beginning.
Your example works if you let SymPy operate on every element of the list, not on the list as a whole. SymPy's subs
fills in variables. SymPy's evalf
converts a constant expression to numbers (because normally SymPy keeps e.g. rationals and sqrt in symbolic form so it keeps a maximal precission).
import sympy as sp
import numpy as np
x = sp.symbols('x')
b = [x , 2*x]
c = [expr.subs(x, 5).evalf() for expr in b]
a = np.array(c)
Upvotes: 5