Programming

\label{sec:computerprog}

The program

The computer for this lab uses Windows and a Python interpreter, iPython. Create a folder for yourself in the astro_comp folder on the Desktop (for example, bob). Double-click the iPython icon on the Desktop – this will open a terminal that you can type commands into. Type the following commands:

> cd > cd Desktop/astro_comp/bob

The code for this lab is written in Python. Python is a programming language that is widely used in astronomy. The sample code is located in astro_comp, and is called nbody.py. Copy this file into your folder in astro_comp.

nbody.py has the basic \(N\)-body code that will calculate the positions and velocities of the bodies for a given number of time-steps. This has been provided so that you can concentrate more on the actual science involved, rather than spending most of your time writing programs. You will, however, need to do a little bit of programming, to calculate things like the total energy of the system, and the planetary temperature and so forth. In this case, the following section may be of some use.

Programming Hints

Talk to your demonstrators for lots of hints on good programming style. But here are a few key hints:

  1. 1.

    Write out your code on paper before you type it in. The most common error novice (and experienced) programmers make is to write half the code before realising that they don’t really understand in detail the algorithm they are trying to code. Make sure you are absolutely clear in your mind about what you want to do before touching finger to keyboard.

  2. 2.

    Write clear, well commented code. Far more time is spent debugging programs than writing them in the first place. If your code is clearly and logically laid out, with lots of comments, it will save you hours in the long term.

  3. 3.

    Give your variables sensible names. If all your variables are called things like XAA you will have to look up what they mean every time you have to alter your code, but something called XVELOCITY is a little more obvious.

  4. 4.

    Test your code. No program longer than about ten lines ever works first time. If you test each little part of your program independently, it will be much easier to debug. Also, never believe what your program is telling you until you’ve tried it on a problem where you know the answer.