sympy计算积分错误

sympy计算积分错误

本文介绍了余弦函数的python sympy计算积分错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试直接从sympy文档中尝试一个示例,但遇到一个奇怪的错误.我正在使用带有sympy 0.7.3.的python 3.2.我一直在ipython笔记本中工作,尽管我认为这不会有所作为.错误是,每当我创建"x"符号并尝试集成math.cos(x)时,都会收到一条错误消息,提示无法将表达式转换为浮点型".

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."

这是一个代码示例.这取自 sympy文档.

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)

导致的错误消息是:

---------------------------------------------------------------------------
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.

推荐答案

您不能将sympy库创建的符号数学表达式与仅用于计算值的普通函数(如math库中的值)混合使用.如果要创建符号表达式,则应始终使用sympy函数(sympy.expsympy.cossympy.log等):

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)

*+-等运算符被sympy库中的对象重载,因此您可以在表达式中使用它们,但不能使用直接计算值的普通函数.

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.

这篇关于余弦函数的python sympy计算积分错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:57