5

I have a variable which may or may not be a sympy class. I want to convert it to a float but I’m having trouble doing this in a general manner:

$ 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 will be testing x, y, z to convert into a float. 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 would raise an exception.


sympy.sympify() unfortunately does not convert to float. if it did then that would be the ideal solution to my problem:

>>> sympy.sympify(z)
3*sqrt(2)
>>> type(sympy.sympify(z))
<class 'sympy.core.mul.Mul'>
mulllhausen
  • 4,225
  • 7
  • 49
  • 71
  • Why not just `sympify` it? – tzaman May 04 '15 at 05:34
  • If all the `sympy` types you're dealing with have the `evalf` method, then maybe you want `try: z= z.evalf(50); except AttributeError: # Code to handle plain ints/floats`. – Marius May 04 '15 at 05:39
  • @tzaman `sympify()` does not output a float afaik – mulllhausen May 04 '15 at 05:50
  • @mulllhausen according to the [docs](http://docs.sympy.org/0.7.1/modules/core.html#sympy.core.sympify.sympify), it should: `it will convert python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc.` – tzaman May 04 '15 at 06:12

2 Answers2

9

All sympy objects inherit from sympy.Basic. To evaluate an 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())
   ...:     
1.41421356237310
ptb
  • 2,138
  • 1
  • 11
  • 16
  • well didn't know that all sympy objects inherit from `sympy.Basic`. – styvane May 04 '15 at 20:39
  • 2
    It's in a well hidden portion of the docs http://docs.sympy.org/latest/modules/core.html?highlight=basic#module-sympy.core.basic. It might be somewhere else too but I can't find it at the moment – ptb May 04 '15 at 20:46
  • Note, that at least in my version of Sympy, matrices are not instances of `sympy.Basic`. – Grwlf Nov 12 '21 at 11:05
0

heh, at the end of the day, it turns out you can just convert a sympy object to float using python's native float conversion function! don't know why i didn't try this straight away...

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

i will use this since it works even if x is a python int or already a python float

mulllhausen
  • 4,225
  • 7
  • 49
  • 71