Skip to content

Commit ab089b7

Browse files
committed
adding example verlet implementation in c++
1 parent 02d8b0a commit ab089b7

File tree

1 file changed

+77
-1
lines changed

1 file changed

+77
-1
lines changed

chapters/computational_physics/verlet.md

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,80 @@ Even though this method is more used than the simple Verlet method mentioned abo
9999

100100
Both of these methods work simply by iterating timestep-by-timestep and can be written straightforwardly in any language. For reference, here are snippets of code that use both the classic and velocity Verlet methods to find the time it takes for a ball to hit the ground after being dropped from a given height.
101101

102-
TODO
102+
#### C++
103+
```c++
104+
/*------------verlet.cpp------------------------------------------------------//
105+
*
106+
* Purpose: Simple demonstration of verlet algorithm
107+
*
108+
*-----------------------------------------------------------------------------*/
109+
110+
#include <iostream>
111+
112+
// Simple function for velocity-verlet
113+
void verlet(double pos, double acc, double dt){
114+
115+
// Note that we are using a temp variable for the previous position
116+
double prev_pos, temp_pos, time;
117+
prev_pos = pos;
118+
time = 0;
119+
120+
while (pos > 0){
121+
time += dt;
122+
temp_pos = pos;
123+
pos = pos*2 - prev_pos + acc * dt * dt;
124+
prev_pos = temp_pos;
125+
}
126+
127+
std::cout << time << '\n';
128+
129+
}
130+
131+
// Simple function for stormer-verlet
132+
void stormer_verlet(double pos, double acc, double dt){
133+
134+
// Note that we are using a temp variable for the previous position
135+
double prev_pos, temp_pos, time, vel;
136+
prev_pos = pos;
137+
vel = 0;
138+
time = 0;
139+
while (pos > 0){
140+
time += dt;
141+
temp_pos = pos;
142+
pos = pos*2 - prev_pos + acc * dt * dt;
143+
prev_pos = temp_pos;
144+
145+
// The acceleration is constant, so the velocity is straightforward
146+
vel += acc*dt;
147+
}
148+
149+
std::cout << time << '\n';
150+
151+
}
152+
153+
// Simple function for velocity-verlet
154+
void velocity_verlet(double pos, double acc, double dt){
155+
156+
// Note that we are using a temp variable for the previous position
157+
double time, vel;
158+
vel = 0;
159+
time = 0;
160+
while (pos > 0){
161+
time += dt;
162+
pos += vel*dt + 0.5*acc * dt * dt;
163+
vel += acc*dt;
164+
}
165+
166+
std::cout << time << '\n';
167+
168+
}
169+
170+
int main(){
171+
172+
verlet(5.0, -10, 0.01);
173+
stormer_verlet(5.0, -10, 0.01);
174+
velocity_verlet(5.0, -10, 0.01);
175+
176+
}
177+
178+
```

0 commit comments

Comments
 (0)