检测变量是否为sympy类型 [英] detect if variable is of sympy type
问题描述
我有一个可能是也可能不是sympy类的变量.我想将其转换为浮点数,但是我通常无法做到这一点:
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
我将测试x
,y
,z
转换为浮点型.请注意,我不能只在x
,y
和z
上运行evalf()
而不进行检查,因为它们可能已经是整数或浮点数,这会引发异常.
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()
不会转换为浮点型.如果这样做的话,那将是解决我的问题的理想解决方案:
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'>
推荐答案
所有sympy对象都从sympy.Basic
继承.要以数值方式计算sympy表达式,只需使用.n()
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
这篇关于检测变量是否为sympy类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!