Midterm 2 - Take Home

Due: Sunday, April 7 at 11:59 pm

Submission: On Courseworks

Skeleton Code: midterm2.zip

Instructions

Please read the instructions carefully. An incorrectly formatted submission may not be counted.

In this take home exam, we will start again from skeleton code. You are given the nbody module from the previous homework. We will implement our code using this module. A tester file (test_nbody.py) is included which you can use to validate your code. To submit, ensure that the nbody module is inside a folder called uni-midterm2 (for for me this would be tkp2108-midterm2). Then compress this folder into a .zip file. For most operating systems, you should be able to right click and have a “compress” option in the context menu. This should create a file called tkp2108-midterm2.zip (with your uni). Submit this on courseworks.

N Body - The Final Chapter

Building on our work in the last two homeworks, we will finally tie together the different pieces of code and finish our n-body simulation. For this part, we only have to implement a few functions and like before we will do so in the nbody module.

Simulation

Our animation is going to call the simulateStep function repeatedly, so let’s implement this.

def simulateStep(objects, delta_t):
    """Given the objects, which have the form [x, y, mass, xvel, yvel], calculate the sum of forces
    acting on each object and update the object with their next position and velocity"""

This is a very simple function that leverages our sumAllForces function, then uses this to update the position and velocity (using our nextPositionAndVelocity function) for each object.

Results

If everything was implemented correctly, the provided test script should show three things:

The two animations should look like this (will vary due to random generation)

Notes

Due to an annoying bug in matplotlib/spyder, the animations may not render properly. To fix, do the following:

In Spyder settings, update the graphics backend to be “automatic”:

Its not recommended to get the animations in JupyterLab, but if you do want to get it running do the following:

Run this once from any cell:

!pip install ipywidgets ipympl

Then you should be able to see the animation inline with this special command %matplotlib ipympl:

Numerical Notes

Because our objects occupy zero space, the skeleton code cheats physics a little bit. This is so we produce prettier pictures in the end. See if you can find it!