# Example: Using Midpoint Step to Simulate Motion

For a recent project, I was tasked with simulating the motion of a ball subject to gravity using three different methods. One of those methods was the Midpoint step.

For those that don’t know, Euler and Midpoint steps are used to approximate the motion of objects knowing the forces and physical factors present in the given system. As such, these methods are often used in Physics-simulation programs.

If you don’t already have a general idea of what these methods are or how they work, I’d recommend going through some of the links I’ve included at the bottom of this post.

## My Code

Here’s the gist I created by modifying some code from my project:

(https://gist.github.com/SIRHAMY/4fef81b52f43cb277a6d)

I’ve declared my function named “midpointStep” that takes in an Eigen::Vector3d object named particle and performs the midpoint step on it.In the first line, I’m calculating the change in velocity that occurs by moving a half time step under the applied forces. Here, it’s simplified so that the only force we’re dealing with is gravity. Recall that acceleration due to gravity is -9.8m/s^2. That’s where the -9.8 comes from.

After calculating this change in velocity, I add it to the original velocity of the particle. Recall from the slides that we’re trying to better approximate the appropriate derivative from the original point by taking one at a half step and using that for the full step. By adding the change in velocity I calculated at the half time step, I’m essentially doing just that – updating the derivative at the original point to match what it would be in half a time step.

After updating the derivative, I can now move the particle according to the midpoint method. Here, I’m simply taking the new velocity I calculated, multiplying it by my time step and adding that to the particle’s position.

**Source:**

- “The Euler Method for the Initial Value Problem” – http://people.sc.fsu.edu/~jburkardt/classes/isc_2011/week10/lecture_18.pdf
- “The Midpoint and Runge Kutta Methods” – https://people.sc.fsu.edu/~jburkardt/classes/isc_2011/week10/lecture_19.pdf
- “The Midpoint Method…” – http://www.usu.edu/mathecon/7360/2StageRunge/2StageRunge.html