-
-
Notifications
You must be signed in to change notification settings - Fork 360
/
Copy pathverlet.cpp
84 lines (64 loc) · 1.99 KB
/
verlet.cpp
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
#include <iomanip>
#include <iostream>
struct timestep {
double time;
double vel;
};
double verlet(double pos, double acc, double dt) {
double prev_pos = pos;
double time = 0;
while (pos > 0) {
time += dt;
double next_pos = pos * 2 - prev_pos + acc * dt * dt;
prev_pos = pos;
pos = next_pos;
}
return time;
}
timestep stormer_verlet(double pos, double acc, double dt) {
double prev_pos = pos;
double time = 0;
double vel = 0;
while (pos > 0) {
time += dt;
double next_pos = pos * 2 - prev_pos + acc * dt * dt;
prev_pos = pos;
pos = next_pos;
// The acceleration is constant, so the velocity is
// straightforward
vel += acc * dt;
}
return timestep { time, vel };
}
timestep velocity_verlet(double pos, double acc, double dt) {
double time = 0;
double vel = 0;
while (pos > 0) {
time += dt;
pos += vel * dt + 0.5 * acc * dt * dt;
vel += acc * dt;
}
return timestep { time, vel };
}
int main() {
std::cout << std::fixed << std::setprecision(8);
// Note that depending on the simulation, you might want to have the
// Verlet loop outside.
// For example, if your acceleration chages as a function of time,
// you might need to also change the acceleration to be read into
// each of these functions.
double time = verlet(5.0, -10, 0.01);
std::cout << "[#]\nTime for Verlet integration is:\n" \
<< time << std::endl;
timestep timestep_sv = stormer_verlet(5.0, -10, 0.01);
std::cout << "[#]\nTime for Stormer Verlet integration is:\n" \
<< timestep_sv.time << std::endl;
std::cout << "[#]\nVelocity for Stormer Verlet integration is:\n" \
<< timestep_sv.vel << std::endl;
timestep timestep_vv = velocity_verlet(5.0, -10, 0.01);
std::cout << "[#]\nTime for velocity Verlet integration is:\n" \
<< timestep_vv.time << std::endl;
std::cout << "[#]\nVelocity for velocity Verlet integration is:\n" \
<< timestep_vv.vel << std::endl;
return 0;
}