问题
I want to have a custom python function which:
- Takes a mathematical expression
f(x)
, bounds of the integralx1,x2
and desired tolerancetol
- Uses
sympy.integrate(y, x)
to check if it has analytical/symbolic solution, if it does then returns the result usingsympy.integrate(y, (x,x1,x2).evalf())
- If it doesn't have an analytical solution out of the
sympy
then it usesscipy.integrate.quad
or other numerical functions to calculate the integral.
The reason is that with this method it will be probably faster and more accurate as a majority of mathematical expressions I'm working with, have analytical integrals.
But I have some issues
- first of all
scipy.integrate.quad
andsympy.integrate
two very different forms of functions. scipy takes pythondef y(x): return f(x)
or lambday=lambda x: f(x)
functions. But sympy takes mathematica expressionsy=f(x)
wherex
has been symbolized bysympy.Symbol('x')
. I need to find a way to convert a sympy symbolic mathematical expression to python/lambda function or vise versa. - my second issue is that sympy does not give any error when the expression doesn't have an analytical integral. it just prints the integral! (for this issue I posted a different question here)
- And last one I don't know how control the tolerance in sympy's
evalf()
. I think forscipy.integrate.quad
one can control the tolerance withepsabs
input?
I would appreciate if you could let me know if it is possible and how to do it.
来源:https://stackoverflow.com/questions/50037208/python-integration-using-both-scipy-and-sympy