|
| 1 | +// Submitted by lolatomroflsinnlos |
| 2 | +public class VerletValues { |
| 3 | + public double time; |
| 4 | + public double vel; |
| 5 | + |
| 6 | + public VerletValues(double time, double vel) { |
| 7 | + this.time = time; |
| 8 | + this.vel = vel; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +public class Verlet { |
| 13 | + static double verlet(double pos, double acc, double dt) { |
| 14 | + |
| 15 | + // Note that we are using a temp variable for the previous position |
| 16 | + double prev_pos, temp_pos, time; |
| 17 | + prev_pos = pos; |
| 18 | + time = 0; |
| 19 | + |
| 20 | + while (pos > 0) { |
| 21 | + time += dt; |
| 22 | + temp_pos = pos; |
| 23 | + pos = pos*2 - prev_pos + acc * dt * dt; |
| 24 | + prev_pos = temp_pos; |
| 25 | + } |
| 26 | + |
| 27 | + return time; |
| 28 | + } |
| 29 | + |
| 30 | + static VerletValues stormer_verlet(double pos, double acc, double dt) { |
| 31 | + |
| 32 | + // Note that we are using a temp variable for the previous position |
| 33 | + double prev_pos, temp_pos, time, vel; |
| 34 | + prev_pos = pos; |
| 35 | + vel = 0; |
| 36 | + time = 0; |
| 37 | + while (pos > 0) { |
| 38 | + time += dt; |
| 39 | + temp_pos = pos; |
| 40 | + pos = pos*2 - prev_pos + acc * dt * dt; |
| 41 | + prev_pos = temp_pos; |
| 42 | + |
| 43 | + // The acceleration is constant, so the velocity is straightforward |
| 44 | + vel += acc*dt; |
| 45 | + } |
| 46 | + |
| 47 | + VerletValues stormerVerlet = new VerletValues(time, vel); |
| 48 | + return stormerVerlet; |
| 49 | + } |
| 50 | + |
| 51 | + static VerletValues velocity_verlet(double pos, double acc, double dt) { |
| 52 | + |
| 53 | + // Note that we are using a temp variable for the previous position |
| 54 | + double time, vel; |
| 55 | + vel = 0; |
| 56 | + time = 0; |
| 57 | + while (pos > 0) { |
| 58 | + time += dt; |
| 59 | + pos += vel*dt + 0.5*acc * dt * dt; |
| 60 | + vel += acc*dt; |
| 61 | + } |
| 62 | + |
| 63 | + VerletValues velocityVerlet = new VerletValues(time, vel); |
| 64 | + return velocityVerlet; |
| 65 | + } |
| 66 | + |
| 67 | + public static void main(String[] args) { |
| 68 | + |
| 69 | + double verletTime = verlet(5.0, -10, 0.01); |
| 70 | + System.out.println("Time for Verlet integration is: " + verletTime); |
| 71 | + |
| 72 | + VerletValues stormerVerlet = stormer_verlet(5.0, -10, 0.01); |
| 73 | + System.out.println("Time for Stormer Verlet integration is: " + stormerVerlet.time); |
| 74 | + System.out.println("Velocity for Stormer Verlet integration is: " + stormerVerlet.vel); |
| 75 | + |
| 76 | + VerletValues velocityVerlet = velocity_verlet(5.0, -10, 0.01); |
| 77 | + System.out.println("Time for velocity Verlet integration is: " + velocityVerlet.time); |
| 78 | + System.out.println("Velocity for velocity Verlet integration is: " + velocityVerlet.vel); |
| 79 | + } |
| 80 | +} |
0 commit comments