J.D.
J.D.

Reputation: 169

Using sympy.integrate on a function that involves int()

I'm trying to integrate functions in Python. scipy.integrate.quad seems to work ok; but just be sure I'd like to check the results against other integration code. It was suggested that I try sympy.integrate. Now the code for the functions I want to integrate contains int(), which I use to convert floats into ints. This is ok for quad, but not for sympy.integrate.

Here's a simple example that reproduces the error:

import sympy

def f(x):
    return sympy.exp(int(x))

sympy.symbols('x')
print(sympy.integrate(f(x),(x,0,2)))

This yields the error: TypeError: can't convert symbols to int

So is there a way to integrate functions that involve int() with scipy.integrate?

Thanks

Upvotes: 0

Views: 310

Answers (1)

Ehren
Ehren

Reputation: 523

To use integrate f must be a SymPy symbolic function which disallows your particular use of int. int(x) where x is a Symbol will always yield a type error however you could represent this symbolically using the floor function:

def f(x):
    return sympy.exp(sympy.floor(x))

However, using floor may defeat some of the purpose of using SymPy in the first place because it will probably prevent discovery of an analytic solution as the following python session demonstrates:

>>> from sympy import *
>>> x = symbols("x")
>>> integrate(exp(floor(x)), (x, 0, 2))  # use of floor prevents evaluated result
Integral(exp(floor(x)), (x, 0, 2))

Though you can use the evalf method to compute a numeric result (which is ultimately performed by mpmath):

>>> integrate(exp(floor(x)), (x, 0, 2)).evalf()
3.7

(perhaps this result suggests sympy could better handle this integral? Wolfram Alpha computes this as 1 + e = 3.71828... so I suppose there is at least a floating point precision bug here too - see comment re ceiling)

In any case, I don't know if you consider that an appropriate result considering the version of f without floor:

>>> integrate(exp(x), (x, 0, 2))
-1 + exp(2)
>>> _.evalf()
6.38905609893065

Upvotes: 1

Related Questions