Skip to content
Advertisement

How can I stop my Runge-Kutta2 (Heun) method from exploding?

I am currently trying to write some python code to solve an arbitrary system of first order ODEs, using a general explicit Runge-Kutta method defined by the values alpha, gamma (both vectors of dimension m) and beta (lower triangular matrix of dimension m x m) of the Butcher table which are passed in by the user. My code appears to work for single ODEs, having tested it on a few different examples, but I’m struggling to generalise my code to vector valued ODEs (i.e. systems).

In particular, I try to solve a Van der Pol oscillator ODE (reduced to a first order system) using Heun’s method defined by the Butcher Tableau values given in my code, but I receive the errors

  • “RuntimeWarning: overflow encountered in double_scalars f = lambda t,u: np.array(... etc)” and
  • “RuntimeWarning: invalid value encountered in add kvec[i] = f(t+alpha[i]*h,y+h*sum)

followed by my solution vector that is clearly blowing up. Note that the commented out code below is one of the examples of single ODEs that I tried and is solved correctly. Could anyone please help? Here is my code:

JavaScript

Advertisement

Answer

Your step size is not small enough. The Van der Pol oscillator with mu=100 is a fast-slow system with very sharp turns at the switching of the modes, so rather stiff. With explicit methods this requires small step sizes, the smallest sensible step size is 1e-5 to 1e-6. You get a solution on the limit cycle already for h=0.001, with resulting velocities up to 150.


You can reduce some of that stiffness by using a different velocity/impulse variable. In the equation

JavaScript

you can combine the first two terms into a derivative,

JavaScript

so that

JavaScript

enter image description here

The second equation is now uniformly slow close to the limit cycle, while the first has long relatively straight jumps when v leaves the cubic v=x^3/3-x.

This integrates nicely with the original h=0.01, keeping the solution inside the box [-3,3]x[-2,2], even if it shows some strange oscillations that are not present for smaller step sizes and the exact solution.

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement