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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With