Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error with python sympy computing integral for cosine function

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.

like image 400
krishnab Avatar asked Aug 16 '13 06:08

krishnab


People also ask

How do you calculate integral in SymPy?

The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression.

What is cos in SymPy?

In simpy, cos() method is cosine function. Using the cos(x) method in simpy module, we can compute the cosine of x. Syntax : sympy.cos(x) Return : Returns the cosine of x. Code #1: Below is the example using cos() method to find cosine function.

How do you evaluate a function using SymPy?

evalf() function and subs() function from sympy is used to evaluate algebraic expressions. Example 1: In this example, we import symbols from sympy package. An expression is created and evalf() function is used to evaluate the expression.


1 Answers

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.

like image 179
Viktor Kerkez Avatar answered Oct 29 '22 19:10

Viktor Kerkez