Modules and Local Variables

Quite often in programming it is useful to divide a calculation up into pieces. You write a small program to do the first part and another to do the second part. Finally you write a third small program that combines the results of the first two into the result that you want. This strategy is nice because you can check that the output of the small programs is correct along the way and it also makes it easier to understand what you’ve done. We’re going to use this strategy to calculate the properties of triangles and circles.

Begin by downloading the picture at this link:  MouseOver

Use the Import command that you studied last week to import this picture into Mathematica. I give an example where I have put the image on my desktop and named it tri. Of course, you should feel free to adapt this to your preferences:

tri=Import["~/Desktop/Triangle.jpg"]

Now, click on the image. You will see a tool bar appear at the bottom,  it looks like this:

In order from left to right these buttons allow you to (i) select, (ii) crop, (iii) transform, (iv) find coordinates on and (v) mask your image. Today we will use the find coordinates tool extensively. Click on this button. As you pass your cursor over the image you will see a cross hair appear that allows you to select a point of the image. Use this cross hair to click on the center of the yellow one ball. Your tool bar will now look like this:

In particular, it will contain the coordinates (x, y) of the point that you clicked in the image. These coordinates are measured from the lower left corner of the image and are given in units of pixels. Click on the centers of the eleven and five balls as well. Press the copy tab and copy the coordinate values into a list called pts:

pts =

The goal of the next part of this coding exercise is to write a funciton that finds the distance (in pixels) between each pair of pool balls. Mathematica allows you to define functions in a simple way using a special syntax, like this:

sq[x_]:= (x^2)

This function computes the square of any number that you feed to it:

{sq[1],sq[2],sq[3],sq[4]}

The syntax is made up of two pieces, the unusual equals symbol with a colon in front of it can be read as `defined as’. In Mathematica parlance it is a `set delayed’ equality. Once the pattern on the left hand side is specified the function evaluates it on the right and you are given the result. The underscore after the x tells Mathematica that this is a variable for the function. Again in Mathematica parlance this is called a pattern. Including the _ warns Mathematica that you expect to replace this variable with values later and that it must search the right hand side and make the replacement everywhere on it.

More sophisticated than a function is a Module. A Module is a small, self-contained program. You can think of a module as being made up of three pieces: the inputs, the local or internal variables, and the outputs. Here is an example that I will explain afterwards:

triArea[a_,b_,c_]:= Module[ (* A module that calculates the area of a triangle given its side lengths a, b, and c. *)
{guts,area},
guts = (a+b+c)(a+b-c)(a-b+c)(-a+b+c); 
area = (1/4)(Sqrt[guts])]

Before evaluating the next input predict what the area of a triangle with side lengths 1, 1 and (Sqrt[2]) is. Then evaluate it in Mathematica.

triArea[1.,1,(Sqrt[2])]

As you can see, a Module is just a function with multiple steps to it and an internal memory. Just like a regular function it has inputs, in our case a, b, and c. Unlike a function it also has internal variables, or “local variables,” in our example these are ‘guts’ and ‘area’. Local variables are quantities that the module remembers while it is evaluating each of its steps but then forgets afterwards. So that if you now type ‘area’ as an input Mathematica won’t have any value assigned to it and will just return the name:

area

This is immensely useful because you can use intuitive names for the variables in your module without globally assigning them to always have the values that they have in the module. After the list of local variables, a Module expects a series of commands it is supposed to execute with each command followed by a semicolon. Finally the module returns the value of the last command that it receives, which does not have a semicolon. In our example this is the value of the area that it last computed.

The grey text after the opening of the Module in the example above is a comment that explains its function. Commenting your code is a very good habit to get into that will save you and others hours of your lives if you do it systematically. I will be looking for comments in your code.

Before turning to your tasks there is one more tool that is likely to come in handy. In our encounters with data in previous labs and with the points from the image above it is often useful to collect all of the information in lists, such as this one

list = {{4,6},{35, 40}, {70, 92}};

You will often want to pick out pieces of the list one at a time. This can be done using double square braces. For example, to return the first sublist in our list use

list[[1]]

To return this sublist’s first entry you have two options:

list[[1]][[1]]

or

list[[1,1]]

These tools for accessing parts of a list are invaluable.

Tasks

1) Write a Module that takes as input the list of points that you found from your picture and returns the lengths of the sides of the triangle. 
2) Feed your results to the Module triArea that we just wrote to find the area of the triangle in pixels. Compare your results with those of your peers to check their correctness.
3) Based on the discussion at the end of the lab preparation period write a module that computes the radius of a circle given three points on it. Use this module to compute the radii needed to do the analysis in each trial of your e/m experiment. Note that for this to work you will have to find a way to convert pixel values to physical distances.