memory allocation) and freed when n = 0. Note that the solution will not be TVD (total
variation diminishing) unless the discretization of f(x) is TVD also.
This isn't strictly a method of lines solver, of course; it may find use whenever some
large, interdependent vector ODE must be stepped forward.
/*
Third order TVD autonomous RK solution. Steps x'(t) = f(x) forward, where x is some
vector of size n.
x is the address of the first element. x must be an array of size n. f is a function as shown
above.
It's fed the address of the first element of x and the index of the element being worked on,
n.
Use n = 0 to free memory.
*/
void RK3(double (*f)(double *x, unsigned int i, unsigned int n), double
*x, unsigned int n, double delta_t){
static double *x1 = NULL, *x2 = NULL;
static unsigned int N = 0;
if(n == 0){
free(x1);
free(x2);
x1 = NULL;
x2 = NULL;
return;
}
if(n > N){
N = n;
x1 = realloc(x1, n*sizeof(double));
x2 = realloc(x2, n*sizeof(double));
}
unsigned int i;
for(i = 0; i != n; i++)
x1
[i] = x[i] + delta_t*f(x, i, n);
for(i = 0; i != n; i++)
x2[i] = 3.0/4.0*x[i] + 1.0/4.0*(x1[i] + delta_t*f(x1, i,
n));
for(i = 0; i != n; i++)
x1[i] = 1.0/3.0*x[i] + 2.0/3.0*(x2[i] + delta_t*f(
x2, i,
n));
memcpy(x, x1, sizeof(double)*n);
}
Fortran 90 equivalent:
subroutine RK3(f, x, n, delta_t, pass)
double precision, external:: f