问题
I want to have a custom python function which:
- Takes a mathematical expression
f(x), bounds of the integralx1,x2and 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
sympythen it usesscipy.integrate.quador 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.quadandsympy.integratetwo 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)wherexhas 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.quadone can control the tolerance withepsabsinput?
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