I have to create a java program using the 4th order Runge-Kutta to integrate the
ID: 3640314 • Letter: I
Question
I have to create a java program using the 4th order Runge-Kutta to integrate the function sin(3*x) from 0 to pi. The function is defined in my class as double f(double t, double y). The code that I came up with for the 4th order Runge-Kutta method ispublic double rk(double x, double y, double step){
double h = step;
double k0 = h * f(x, y);
double k1 = h * f(x + 0.5 * h, y + 0.5 * k0);
double k2 = h * f(x + 0.5 * h, y + 0.5 * k1);
double k3 = h * f(x + h, y + k2);
return y + 1.0/6.0 * (k0 + 2 * k1 + 2 * k2 + k3);
My question is, how would I integrate the function sin(3*x) from 0 to pi using the Runge-Kutta method? Any tips on how to get started would be much appreciated.
Explanation / Answer
You have to call following function with loop as many steps as you need to compute the y value.
public double rk(double x, double y, double step) {
double h = 1.0/step;
x = step*h;
double k0 = h * f(x, y);
double k1 = h * f(x + h/2, y + k0/2);
double k2 = h * f(x + h/2, y + k1/2);
double k3 = h * f(x + h, y + k2);
return y = k0/6 + k2/3 + k3/3 + k4/6;
}
// Derivative
public static double f(double x, double y) {
return x * Math.sqrt(1 + y * y);
}