Determine if a variable is of type sympy

I have a variable that may or may not be a sympy class. I want to convert it to float, but Im having a hard time doing it in general:

$ python
Python 2.7.3 (default, Dec 18 2014, 19:10:20) 
[GCC 4.6.3] on linux2
>>> import sympy
>>> x = sympy.sqrt(2)
>>> type(x)
<class 'sympy.core.power.Pow'>
>>> y = 1 + x
>>> type(y)
<class 'sympy.core.add.Add'>
>>> z = 3 * x
>>> type(z)
<class 'sympy.core.mul.Mul'>
>>> if isinstance(z, sympy.core):
...     z = z.evalf(50) # 50 dp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types


I'll be testing x

, y

, z

for conversion to float. please note that I can't just run evalf()

on x

, y

and z

without checking, because they might be integers or floats already and this will throw an exception.


unfortunately not convertible to float. if it were, this would be the perfect solution to my problem:

>>> sympy.sympify(z)
>>> type(sympy.sympify(z))
<class 'sympy.core.mul.Mul'>



source to share

3 answers

How about this:

isinstance(z, tuple(sympy.core.all_classes))




All simplex objects inherit from sympy.Basic

. To evaluate sympy expression numerically, just use.n()

In [1]: import sympy

In [2]: x = sympy.sqrt(2)

In [3]: x
Out[3]: sqrt(2)

In [4]: x.n()
Out[4]: 1.41421356237310

In [5]: if (isinstance(x, sympy.Basic)):
   ...:     print(x.n())




heh in the end it turns out you can just convert your sympy object to float using python's float conversion function! don't know why i didn't try it right away ...

>>> import sympy
>>> x = sympy.sqrt(2)
>>> float(x)


i will use this since it works even if x

is python int or already floating python



All Articles