Session 6: Distance Measures - Module B: 1D and 2D

1. Discussion: Computing Distances

Running from a zombie. (Distances on a line.)
What if we have a 2 dimensional plane?

2. 1D Distance Code

I've written a program to calculate distances in one dimension.

  1. Save to your programs folder.
  2. Open the code up in gedit and take a look at it.

Find the line where the distance is calculated. How does it compare with the formula we discussed earlier?

Try running the program so you get a feel for how it works:

  1. Open a terminal window.
  2. Change the directory to your programs directory:

    cd programs/

  3. Start IPython with the command:


  4. From IPython, run the program:


  5. Now that the program is loaded you can try more values by simply calling the function in ipython with different values.


  6. Try more values, but remember if you change the program in gedit you need to rerun it in ipython (step 4).

3. 2D Distance Code

Now you can make the program a little more useful by converting it to compute distances in two dimensions!

First, save a copy of the program so you still have the original:

  1. Click File in the lefthand corner of gedit, then choose Save as....
  2. Save the program as

You're ready to change the code so that it calculates the distance between two points in a two-dimensional plane.

  1. You will need to add two new variables for the y coordinates of the two points as parameters. Make sure they have different names than the ones already there!
  2. Then you'll need to change the distance calculation line to use the formula for two-dimensional distances.

There are a couple things you'll find useful:

Run your program in IPython to test it. If you use (x1, y1) = (1, 1) and (x2, y2) = (4, 5), your program should print 5.0 for the distance.

Once you have the distance calculation working, uncomment the last line of the program by erasing the hash symbol to generate a plot to go with your distance calculation.

Remember to save your favorite plot and answer these questions on your webpage!