Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.Math;
- //maybe change the names of variables for the functions to make it less confusing?
- public class RungeKutta {
- //change N, h and initial values according to what we need
- int N = 20; /** number of steps */
- double h = 0.01; /** step size */
- double x0 = 0.0; /** initial value */
- double v0 = 1.0; /** initial value */
- double t[] = new double[N]; /** time after i-th step */
- double x[] = new double[N];
- double v[] = new double[N];
- public RungeKutta() {
- for(int i = 0; i < N; i++)
- t[i] = i;
- x[0] = x0;
- v[0] = v0;
- for(int j = 1; j < N; j++) {
- x[j] = 0;
- v[j] = 0;
- }
- }
- public double f1(double t1, double x1, double v1) {
- return v1;
- }
- //change this into our function
- public double f2(double t2, double x2, double v2) {
- return -v2 -Math.sin(x2) + Math.sin(t2);
- }
- public void rungeKutta() {
- double k1, k2, k3, k4;
- double l1, l2, l3, l4;
- for(int i = 0; i < (t.length-1); i++) {
- k1 = f1(t[i], x[i], v[i]);
- l1 = f2(t[i], x[i], v[i]);
- k2 = f1(t[i] + h/2, x[i] + h*k1/2, v[i] + h*l1/2);
- l2 = f2(t[i] + h/2, x[i] + h*k1/2, v[i] + h*l1/2);
- k3 = f1(t[i] + h/2, x[i] + h*k2/2, v[i] + h*l2/2);
- l3 = f2(t[i] + h/2, x[i] + h*k2/2, v[i] + h*l2/2);
- k4 = f1(t[i] + h, x[i] + h*k3, v[i] + h*k3);
- l4 = f2(t[i] + h, x[i] + h*k3, v[i] + h*k3);
- x[i+1] = x[i] + h/6*(k1 + 2*k2 + 2*k3 + k4);
- v[i+1] = v[i] + h/6*(l1 + 2*l2 + 2*l3 + l4);
- t[i+1] = t[i] + h;
- }
- for(int i = 0; i < t.length; i++)
- System.out.println("t = " + t[i] + ", x = " + x[i] + " , v = " + v[i]);
- }
- public static void main(String[] args) {
- RungeKutta RK = new RungeKutta();
- RK.rungeKutta();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement