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
z to convert into a float. note that I can't just run
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'>