Python integration using both scipy and sympy

我的未来我决定 提交于 2019-12-11 05:48:59

问题


I want to have a custom python function which:

  1. Takes a mathematical expression f(x) , bounds of the integral x1,x2 and desired tolerance tol
  2. Uses sympy.integrate(y, x) to check if it has analytical/symbolic solution, if it does then returns the result using sympy.integrate(y, (x,x1,x2).evalf())
  3. If it doesn't have an analytical solution out of the sympy then it uses scipy.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 and sympy.integrate two very different forms of functions. scipy takes python def y(x): return f(x) or lambda y=lambda x: f(x) functions. But sympy takes mathematica expressions y=f(x) where x has been symbolized by sympy.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 for scipy.integrate.quad one can control the tolerance with epsabs 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!