Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. import java.lang.Math;
  2.  
  3. //maybe change the names of variables for the functions to make it less confusing?
  4. public class RungeKutta {
  5.  
  6. //change N, h and initial values according to what we need
  7. int N = 20; /** number of steps */
  8. double h = 0.01; /** step size */
  9. double x0 = 0.0; /** initial value */
  10. double v0 = 1.0; /** initial value */
  11. double t[] = new double[N]; /** time after i-th step */
  12. double x[] = new double[N];
  13. double v[] = new double[N];
  14.  
  15. public RungeKutta() {
  16.  
  17. for(int i = 0; i < N; i++)
  18. t[i] = i;
  19.  
  20. x[0] = x0;
  21. v[0] = v0;
  22.  
  23. for(int j = 1; j < N; j++) {
  24.  
  25. x[j] = 0;
  26. v[j] = 0;
  27. }
  28. }
  29.  
  30. public double f1(double t1, double x1, double v1) {
  31.  
  32. return v1;
  33. }
  34.  
  35. //change this into our function
  36. public double f2(double t2, double x2, double v2) {
  37.  
  38. return -v2 -Math.sin(x2) + Math.sin(t2);
  39. }
  40.  
  41. public void rungeKutta() {
  42.  
  43. double k1, k2, k3, k4;
  44. double l1, l2, l3, l4;
  45.  
  46. for(int i = 0; i < (t.length-1); i++) {
  47.  
  48. k1 = f1(t[i], x[i], v[i]);
  49. l1 = f2(t[i], x[i], v[i]);
  50. k2 = f1(t[i] + h/2, x[i] + h*k1/2, v[i] + h*l1/2);
  51. l2 = f2(t[i] + h/2, x[i] + h*k1/2, v[i] + h*l1/2);
  52. k3 = f1(t[i] + h/2, x[i] + h*k2/2, v[i] + h*l2/2);
  53. l3 = f2(t[i] + h/2, x[i] + h*k2/2, v[i] + h*l2/2);
  54. k4 = f1(t[i] + h, x[i] + h*k3, v[i] + h*k3);
  55. l4 = f2(t[i] + h, x[i] + h*k3, v[i] + h*k3);
  56.  
  57. x[i+1] = x[i] + h/6*(k1 + 2*k2 + 2*k3 + k4);
  58. v[i+1] = v[i] + h/6*(l1 + 2*l2 + 2*l3 + l4);
  59. t[i+1] = t[i] + h;
  60.  
  61. }
  62.  
  63. for(int i = 0; i < t.length; i++)
  64. System.out.println("t = " + t[i] + ", x = " + x[i] + " , v = " + v[i]);
  65. }
  66.  
  67. public static void main(String[] args) {
  68.  
  69. RungeKutta RK = new RungeKutta();
  70. RK.rungeKutta();
  71.  
  72. }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement