Python: Unable to solve a differential equation using odeint with signum function

二次信任 提交于 2019-12-06 08:51:19

The integrator employed by odeint (and probably all integrators you find implemented) are based on the assumption that your derivative (f) is continuous (and has a continuous derivative) during each step. The signum function obviously breaks this requirement. This causes the error estimates to be very high, no matter how small the step size, which in turn leads to an overly small step size and the problems you have been experiencing.

There are two general solutions to this:

  1. Choose your step size such that the sign flip exactly falls on a step. (This may be horribly tedious.)

  2. Replace the signum function with a very steep sigmoid, which should be fine and even more realistic for most applications. In your code, you could use

    sign = lambda x: np.tanh(100*x)
    

    instead of np.sign. The factor 100 here controls the steepness of the sigmoid. Choose it sufficiently high to reflect the behaviour you actually need. If you choose it excessively high, this may negatively affect your runtime as the integrator will adapt the step size to be unnecessarily small.

In your case, setting a small absolute tolerance also seems to be working, but I would not rely on this:

sol = odeint(f,y0,t,mxstep=50000,atol=1e-5)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!