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.
- Save 1Ddistance.py to your programs folder.
- 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:
- Open a terminal window.
- Change the directory to your programs directory:
- Start IPython with the command:
- From IPython, run the program:
- Now that the program is loaded you can try more values by simply calling the function in ipython with different values.
- 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:
- Click File in the lefthand corner of gedit, then choose Save as....
- Save the program as 2Ddistance.py.
You're ready to change the code so that it calculates the distance between two points in a two-dimensional plane.
- 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!
- 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:
- To square an expression in Python, type x**2. This works either for a single variable like x, or more complicated expressions like x + y. Ex: (x + y)**2
- To find the square root of an expression, type sqrt(x). Like squaring, this can also have a more complicated expression passed in.
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!