forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Verlet.java
84 lines (66 loc) · 2.5 KB
/
Verlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class Verlet {
private static class VerletValues {
public double time;
public double vel;
public VerletValues(double time, double vel) {
this.time = time;
this.vel = vel;
}
}
static double verlet(double pos, double acc, double dt) {
// Note that we are using a temp variable for the previous position
double prev_pos, temp_pos, time;
prev_pos = pos;
time = 0;
while (pos > 0) {
time += dt;
temp_pos = pos;
pos = pos*2 - prev_pos + acc * dt * dt;
prev_pos = temp_pos;
}
return time;
}
static VerletValues stormer_verlet(double pos, double acc, double dt) {
// Note that we are using a temp variable for the previous position
double prev_pos, temp_pos, time, vel;
prev_pos = pos;
vel = 0;
time = 0;
while (pos > 0) {
time += dt;
temp_pos = pos;
pos = pos*2 - prev_pos + acc * dt * dt;
prev_pos = temp_pos;
// The acceleration is constant, so the velocity is straightforward
vel += acc*dt;
}
return new VerletValues(time, vel);
}
static VerletValues velocity_verlet(double pos, double acc, double dt) {
// Note that we are using a temp variable for the previous position
double time, vel;
vel = 0;
time = 0;
while (pos > 0) {
time += dt;
pos += vel*dt + 0.5*acc * dt * dt;
vel += acc*dt;
}
return new VerletValues(time, vel);
}
public static void main(String[] args) {
double verletTime = verlet(5.0, -10, 0.01);
System.out.println("[#]\nTime for Verlet integration is:");
System.out.println(verletTime);
VerletValues stormerVerlet = stormer_verlet(5.0, -10, 0.01);
System.out.println("[#]\nTime for Stormer Verlet integration is:");
System.out.println(stormerVerlet.time);
System.out.println("[#]\nVelocity for Stormer Verlet integration is:");
System.out.println(stormerVerlet.vel);
VerletValues velocityVerlet = velocity_verlet(5.0, -10, 0.01);
System.out.println("[#]\nTime for velocity Verlet integration is:");
System.out.println(velocityVerlet.time);
System.out.println("[#]\nVelocity for velocity Verlet integration is:");
System.out.println(velocityVerlet.vel);
}
}