2

I would like to implement my own basic Runge-Kutta 4 integrator in Python. The format should be something like this:

---- EXAMPLE set of equations ----
f1 = lambda x: x**2
f2 = lambda y: y**2
.
.
.
fn = lambda n: n**2
f = [f1, f2, f3, ... , fn]

result = integrate(f, other arguments [e.g. stepsize etc.])

---- result should be of format ----
result = [result1 result2 result3 ... resultn]

So basically I want to be able to define, for example, a set of three equations of motion, and be able to pass these to a function and access them to manipulate these equations inside of that function. How is that possible?

Ideally, I want to achive something similar to Matlabs ode45 function, which can be called for example as follows:

% ---- file 1 ---- %
function xp=F(t,x)
xp=zeros(2,1);
xp(1)=x(2);
xp(2)=-t*x(1)+exp(t)*x(2)+3*sin(2*t); 

% ---- file 2 ---- %
[t,x]=ode45(’file 1’,[t0,tf],[x10,x20]);

% where t0 tf initial and final values of t
% x10 x20 initial values of x

Note 1:
I have already looked at the source for dopri5 in SciPy but it is implemented in C and far too advanced for my purposes.

Note 2:
Let me know if what I've written above is not clear at all, which

1
  • FYI you know this will probably be slow, right? Commented Mar 8, 2012 at 19:39

1 Answer 1

2

DISCLAIMER: Python isn't designed for writing this sort of low-level numeric stuff. It's certainly good at managing it -- numpy is a module specifically for handling large numeric datasets and doing calculations like this on them -- but the actual number-crunching is done in low-level C or Fortran for speed. Writing your own integrator is an interesting learning exercise, but it won't teach you that much about how Python is used normally. That said:


You can do exactly what you asked for.

>>> def integrate(fs):
...     print fs[0](1)
... 
>>> f1 = lambda x: x**2
>>> f2 = lambda x: x**3
>>> 
>>> fs = (f1, f2)
>>> 
>>> integrate(fs)
1

This makes sense, because functions are first-class objects in Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, this works indeed. Thanks! I was aware of the fact that Python isn't made for such tasks, but as an exercise it will do. After prototyping it I might still outsource the routine. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.