Search code examples
pythonsympysymbolic-math

How to check if an expression is a sympy vector


How can I tell if a sympy expression is a vector? See the following example:

from sympy import *
from sympy.vector import *
N = CoordSys3D('N')
x = symbols('x')
v = x * N.i + x**2 * N.j + x**3 * N.k
type(v)
# sympy.vector.vector.VectorAdd

vf=factor(v)
vfs = vf.as_ordered_factors()
vfs
#[x, N.i + N.j*x + N.k*x**2]

type(vfs[1])
# sympy.core.add.Add

After v was factored, none of its factors have a sympy.vector... type. How can I tell which one of its factors is a vector? Is there a test for that?


Solution

  • SymPy has a variety of ways to search/parse expressions. Something that may work for you is the as_independent method:

    >>> vf.as_independent(Vector)
    (x, N.i + N.j*x + N.k*x**2)
    

    You Vector-dependent part of vf will be the rightmost element.