问题
So I was trying an example directly from the sympy documentation and I am getting a strange error. I am using python 3.2 with sympy 0.7.3. I have been working in the ipython notebook, though I don't think that should make a difference. The error is that whenever I create a "x" symbol and try to integrate the math.cos(x), I get an error saying "can't convert expression to float."
Here is a code example. This is taken from the sympy documentation.
import sympy
import math
x = sympy.Symbol('x')
sympy.integrate(x**2 * math.exp(x) * math.cos(x), x)
The error message that results is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-123-84e55454fb60> in <module>()
----> 1 sympy.integrate(x**2 * math.exp(x) * math.cos(x), x)
/usr/local/lib/python3.2/dist-packages/sympy/core/expr.py in __float__(self)
242 if result.is_number and result.as_real_imag()[1]:
243 raise TypeError("can't convert complex to float")
--> 244 raise TypeError("can't convert expression to float")
245
246 def __complex__(self):
TypeError: can't convert expression to float
Any suggestions would be appreciated.
回答1:
You cannot mix the symbolic mathematical expressions created by the sympy
library with normal functions that just calculate a value (like the ones from the math
library. If you're creating a symbolic expression, you should always use the sympy
functions (sympy.exp
, sympy.cos
, sympy.log
, etc.):
x = sympy.Symbol('x')
sympy.integrate(x**2 * sympy.exp(x) * sympy.cos(x), x)
Operators such as *
, +
, -
... Are overloaded by objects in the sympy
library so you can use them in your expressions, but you cannot use normal functions that directly calculate values.
来源:https://stackoverflow.com/questions/18267470/error-with-python-sympy-computing-integral-for-cosine-function