CoCalc Public FilesLabs / Lab2 / Lab2.ipynb
Author: Makayla Mohrland
Views : 77
Description: lab 2
Compute Environment: Ubuntu 20.04 (Default)

# Lab 2: Lists, Loops and Animation

One of the great things about computers is their ability to repeat tasks quickly, accurately and without getting bored. We will take advantage of this capability many times during this course. This lab will introduce loops, which perform such repetition, and use them to create animations. First, however, we’ll take a look at some of the different kinds of objects SageMath works with.

### Types of Things

In the previous lab, you worked with numbers and functions. You also made plots, and in the process of making them, you encountered words enclosed in quotation marks. For example, when you want to make a plot red, you have to put the word "red" in quotation marks. Such words are called strings, which is short for "character strings". Strings allow computers to handle words, phrases, and typographic symbols. Strings can include numbers, not just letters. But when numbers are treated as strings, they act quite differently from regular numbers.

Exercise 1. Enter the following code into SageMath and compare the outputs.
>>a=5
>>show(a)
>>b="5"
>>show(b)


Exercise 2. What happens when you add 1 to a? To b?

In [10]:
a=5
show(a)
b="5"
show(b)

$5$
$5$
In [11]:
a+1

6
In [12]:
b+1

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-d18ca6847e56> in <module>() ----> 1 b+Integer(1) /ext/sage/sage-9.1/local/lib/python3.7/site-packages/sage/rings/integer.pyx in sage.rings.integer.Integer.__add__ (build/cythonized/sage/rings/integer.c:12304)() 1801 return y 1802 -> 1803 return coercion_model.bin_op(left, right, operator.add) 1804 1805 cpdef _add_(self, right): /ext/sage/sage-9.1/local/lib/python3.7/site-packages/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel.bin_op (build/cythonized/sage/structure/coerce.c:11178)() 1253 # We should really include the underlying error. 1254 # This causes so much headache. -> 1255 raise bin_op_exception(op, x, y) 1256 1257 cpdef canonical_coercion(self, x, y): TypeError: unsupported operand parent(s) for +: '<class 'str'>' and 'Integer Ring' 
In [ ]:
#there was an error for the b funciton


Remark. There is a little bit of vocabulary you should be aware of, as you may see it online and in the SageMath documentation. While the fundamental idea to understand is that different types of objects behave differently even though they may look alike, programmers often use the word "type" for simple objects like strings and numbers and "class" for more complex ones like graphs. Just think "type" when you see “class” and you’ll be fine. You can find out what the type of an object is using the type command.

>>type(a)
<type ’sage.rings.integer.Integer’>


This output means that a is a SageMath integer.

>>type(b)
<type 'str'>


This output means that b is a character string.

Exercise 3. Find the types of the number 0.2 and the graph (plot) of $f(x) = x^2$. (Hint: Look back at the end of Lab 1 fo how to make a plot).
In [14]:
type (0.2)

<class 'sage.rings.real_mpfr.RealLiteral'>
In [17]:
type(plot(x^2))

<class 'sage.plot.graphics.Graphics'>

In the above exercises, the variables a and b look the same when displayed using show but act very differently when used in an arithmetical calculation. This happens because a is the integer 5 while b is the character string "5". We say these variables have different types, which just means they’re different kinds of things. The type of a is "integer", while the type of b is "string". This explains what you saw in Exercise 2. Adding 1 to an integer is not a problem, but adding 1 to a character string makes no sense and results in an error.
Actually, addition is defined for strings in SageMath. Here’s how it works.

>>"5"+"1"
'51'


You can see that the + symbol (or "operator") still embodies the idea of "putting things together". However, "putting things together" means something different for integers than for character strings or for the plots in Lab 1 #33, so the exact meaning of + changes depending on the types of objects it’s acting on. (Programmers say this makes + an overloaded operator.)

Exercise 4. Give another example of a type of SageMath object for which addition is defined and explain what addition means for that type of data.
In [18]:
"5"+"3"
#this function is putting the two numbers together instead of adding them

'53'

### Lists

Scientific data and the outputs of model simulations often come in the form of lists of numbers. SageMath gives us many tools for working with such lists and tables.

You make a list by enclosing its elements, separated by commas, in square brackets:

["Bacteria", "Protists", "Plants", "Fungi", "Animals"]
[2,3,5,7,11,13]


Each element of a list can be accessed by its position in the list, typically called its index. In Python, indexing starts with 0, so the first element of a list with $k$ elements has index 0 and the last element has index $k − 1$.

Example 1. Enter the list of biological kingdoms into SageMath and call it kingdoms.

>>kingdoms = ["Bacteria", "Protists", "Plants", "Fungi", "Animals"]


To access the first element of this list, enter:

>>kingdoms[0]
'Bacteria'

Exercise 5. A bacteria population is doubling every hour. Its sizes at different times are 100, 200, 400 and 800. Make a list of these values.

[100, 200, 400, 800]

Exercise 6. Assign the list of bacteria population sizes to the variable bacteria. (You can just copy and paste the list.)

Exercise 7. Find the type of the variable bacteria from the previous exercise.

Exercise 8. What is the value of bacteria[1]? What about bacteria[0]? First, answer without entering the command into SageMath. Then, use SageMath to check your answers.

In [5]:
[100,200,400,800]

[100, 200, 400, 800]
In [6]:
bacteria=[100,200,400,800]

In [6]:
type(bacteria)

<class 'list'>
In [7]:
bacteria[1]
bacteria[0]

100

You can add an element to the end of a list using listname.append(element). (The generic names listname or list are just placeholders for the real name of your list.) For instance if you wanted to add the string “Archaea” to the list named kingdoms, the code would look something like this:

>> kingdoms.append("Archaea")


Note that the above code does not output anything to the screen. This is because the append() function only tells the computer to save its input to specified list. To see the result, we would have to type kingdoms and evaluate the cell.

Exercise 9. Append the number 1600 to bacteria and call it to display its value. Don’t paste or retype any output.
[100, 200, 400, 800, 1600]

Exercise 10. What is the next value of the population? Append it to the list.

Exercise 11. What would happen in the example above if we did kingdoms.append("Archaea") twice before viewing kingdoms? Try this out and explain why you got the result that you did.

In [16]:
bacteria.append(1600)
bacteria

[100, 200, 400, 800, 1600, 3200, 1600, 1600]
In [18]:
bacteria.append(3200)
bacteria

[100, 200, 400, 800, 1600, 3200, 1600, 1600, 3200, 3200]
In [ ]:
#displaying kingdom.append(archea) twice, would add archea to the list twice. This because now multiple strings of archea have been inputed


### Plotting lists

To plot the entries in a list, use the list_plot function. If you give this function a single list of numbers as an input, it will plot each number against its position in the list. For example, the command list_plot(bacteria) plots the list of population sizes you just created in Example 6, producing the graph below.

Notice that the $x$-coordinate of the first point is 0, not 1. This happens because SageMath starts counting at zero, so the index of the first element of a list is 0.

Exercise 12. Plot the list [3,5,7,9,11].
In [25]:
odds=[3,5,7,9,11]
list_plot(odds)


Often, we will need to plot lists of points. For example, suppose we have the points (1,2), (2,1), (3,4), and (4,3), with the first number in the ordered pair an $x$-coordinate and the second a $y$-coordinate. How do we plot these points in SageMath?

First, we enter the list of points:

>>g = [(1,2), (2,1), (3,4), (4,3)]


Then, we use the list_plot function to produce the figure below

>>list_plot(g)


This plot is technically correct, but the points are a little hard to see. To make them more noticeable, we might color them red and change their size. The command list_plot(g, color="red", size=30) produces the second figure below.

Exercise 13. Define your own list of pairs of values and plot it. Make sure your plot is legible.
In [37]:
evens=[(2,2), (4,4),(6,6),(8,8)]

In [38]:
list_plot(evens)


Whether you’re plotting a list of numbers using list_plot() or a mathematical function using plot(), you can label the axes of the plot using the axes_labels plotting option.

Example 2. Adding axes labels to our plot of bacteria population sizes.
list_plot(bacteria, axes_labels=["time", "population"])


Notice that axes_labels is a variable that we set equal to a list of labels. In SageMath, square brackets always mean that a list is involved. Another feature of list_plot is the ability to connect the points of the list together. This is accomplished by using the plotjoined option:

Example 3. Making the bacteria graph plot joined and adding axes labels:
list_plot(bacteria, axes_labels=["time","population"],plotjoined = True)


Note that the value of plotjoined is either True or False. This type of data is called a boolean. You will learn more about this data type in the future. Now that we know how to label axes and join points, we should do so whenever it is reasonable to do so. We should join points whenever we want to see a curve. Labeling axes is a good way to keep track of which values correspond to which axes, especially when we plot lists against each other.

However, list_plot requires a list of points, not two lists of numbers, as input. To avoid typing long lists of points and all the required parentheses by hand, we turn to the function zip. This function takes two lists and turns them into a list of ordered pairs. (It can also take more than two lists and turn them into a list of $n$-tuples.) Actually, for reasons that are beyond the scope of this class, we have to next apply the list function to the output of zip. For example:

>>list(zip([1,2,3], [4,5,6]))
[(1, 4), (2, 5), (3, 6)]
>>list(zip([1,2,3], [4,5,6], [7,8,9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


This is the kind of input that list_plot needs. It’s common to nest the list(zip()) command inside the list_plot command, as below.

>>list_plot(list(zip([1,2,3], [4,5,6])))


This means the same thing as:

>>pairs = list(zip([1,2,3], [4,5,6]))
>>list_plot(pairs)

Exercise 14. You are studying populations of hippos and crocodiles in a river in Africa. Over five years, the hippo population at your study site has been 62, 81, 75, 90 and 67. In the same years, the crocodile population has been 20, 34, 18, 25 and 31. Plot the system’s states in hippo-crocodile space, labeling your axes appropriately and making the points red.
In [12]:
hippo_crocodile=list(zip([62,81,75,90,67], [20,34,18,25,31]))
list_plot(hippo_crocodile, axes_labels=["hippos","crocodiles"],color="red")


The zip function is very helpful in plotting time series graphs. All you need to do is make a list of time values and zip it with the values of your state variable. It is usually used together with the list function which converts the output of zip into a list.

Exercise 15. The list in Exercise 10 gives the size of a population of bacteria at one-hour intervals. Since one hour is 1/24 of a day, create a list of time points for these observations with time in days. Then, plot a time series graph of the population.
In [13]:
bacteria
time=[1.0/24,2.0/24,3.0/24,4.0/24,5.0/24,6.0/24]
btime=list(zip(time,bacteria))
list_plot(btime, axes_labels=["time","bacteria"])


Having developed some basic tools, we will now use them to work with real data. Your worksheet contains lists called wt5_time, wt5_heartrate and wt5_temp. These lists contain heart rate and body temperature data for a wild type (control) rat, measured over 72 hours as part of a real study of circadian rhythms.

Exercise 16. Plot time series of the rat’s heart rate and body temperature, using different colors. Make sure the plot uses the given time values, not just 0, 1, 2.... and that your axes are labeled.

Exercise 17. Compare the plots and describe any relationships you observe.

Exercise 18. Plot the data as a trajectory in temperature-heart rate space. Make sure to label your axes.

In [20]:
wt5_time = [0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3,3.25,3.5,3.75,4,4.25,4.5,4.75,5,5.25,5.5,5.75,6,6.25,6.5,6.75,7,7.25,7.5,7.75,8,8.25,8.5,8.75,9,9.25,9.5,9.75,10,10.25,10.5,10.75,11,11.25,11.5,11.75,12,12.25,12.5,12.75,13,13.25,13.5,13.75,14,14.25,14.5,14.75,15,15.25,15.5,15.75,16,16.25,16.5,16.75,17,17.25,17.5,17.75,18,18.25,18.5,18.75,19,19.25,19.5,19.75,20,20.25,20.5,20.75,21,21.25,21.5,21.75,22,22.25,22.5,22.75,23,23.25,23.5,23.75,24,24.25,24.5,24.75,25,25.25,25.5,25.75,26,26.25,26.5,26.75,27,27.25,27.5,27.75,28,28.25,28.5,28.75,29,29.25,29.5,29.75,30,30.25,30.5,30.75,31,31.25,31.5,31.75,32,32.25,32.5,32.75,33,33.25,33.5,33.75,34,34.25,34.5,34.75,35,35.25,35.5,35.75,36,36.25,36.5,36.75,37,37.25,37.5,37.75,38,38.25,38.5,38.75,39,39.25,39.5,39.75,40,40.25,40.5,40.75,41,41.25,41.5,41.75,42,42.25,42.5,42.75,43,43.25,43.5,43.75,44,44.25,44.5,44.75,45,45.25,45.5,45.75,46,46.25,46.5,46.75,47,47.25,47.5,47.75,48,48.25,48.5,48.75,49,49.25,49.5,49.75,50,50.25,50.5,50.75,51,51.25,51.5,51.75,52,52.25,52.5,52.75,53,53.25,53.5,53.75,54,54.25,54.5,54.75,55,55.25,55.5,55.75,56,56.25,56.5,56.75,57,57.25,57.5,57.75,58,58.25,58.5,58.75,59,59.25,59.5,59.75,60,60.25,60.5,60.75,61,61.25,61.5,61.75,62,62.25,62.5,62.75,63,63.25,63.5,63.75,64,64.25,64.5,64.75,65,65.25,65.5,65.75,66,66.25,66.5,66.75,67,67.25,67.5,67.75,68,68.25,68.5,68.75,69,69.25,69.5,69.75,70,70.25,70.5,70.75,71,71.25,71.5,71.75,72]
wt5_temp = [35.77,37.23,37.32,36.75,36.09,35.68,35.46,35.35,35.3,35.21,35.21,35.25,35.4,35.92,36.52,36.56,36.07,35.6,35.39,35.27,35.09,34.91,34.85,34.81,34.78,34.85,34.88,34.96,35.05,34.96,34.8,34.76,34.73,34.74,35.18,35.91,36.31,36.39,36.12,35.59,35.27,35.17,35,34.69,34.53,34.85,35.49,35.98,35.89,35.34,35,35.37,36.25,36.62,36.51,36.77,37.32,37.76,37.95,38.01,38.03,38.05,38.02,37.95,37.93,37.88,37.69,37.53,37.51,37.56,37.61,37.6,37.6,37.65,37.61,37.51,37.14,36.4,35.72,35.44,35.36,35.27,35.32,35.65,36.2,36.61,36.96,37.33,37.62,37.8,37.86,37.84,37.82,37.81,37.75,37.68,37.63,37.52,37.3,36.82,36.13,35.68,35.52,35.57,35.66,35.62,35.42,35.28,35.64,36.13,36.01,35.61,35.37,35.29,35.2,35.15,35.18,35.18,35.07,35.02,35.05,35,35.02,35.1,35.02,35.08,35.49,35.89,35.78,35.38,35.11,34.96,34.97,35.09,35.07,34.85,34.69,34.99,35.45,35.38,35.02,34.81,34.83,35.34,36.18,36.83,37.14,37.06,36.5,35.94,36.06,36.65,37.23,37.66,37.86,37.84,37.73,37.68,37.67,37.63,37.48,37.3,37.45,37.7,37.78,37.8,37.78,37.71,37.68,37.75,37.75,37.69,37.6,37.48,36.91,36.01,35.3,35.09,35.12,35.21,35.41,35.84,36.59,37.13,37.42,37.64,37.71,37.77,37.91,37.96,37.92,37.87,37.76,37.59,37.27,36.75,36.08,35.53,35.23,35.05,34.95,35.06,35.26,35.35,35.39,35.26,35.13,35.37,36.06,36.48,36.11,35.6,35.31,35.09,34.94,34.96,34.97,34.89,34.88,34.96,35.07,34.99,34.77,34.62,34.67,34.85,35.08,35.5,35.63,35.25,34.9,34.8,34.81,34.85,34.87,34.84,34.92,35.35,36.03,36.64,37.08,37.23,36.85,36.07,35.64,35.75,35.89,36.23,36.96,37.56,37.87,37.97,37.98,37.93,37.81,37.65,37.58,37.62,37.49,36.99,36.27,35.89,36.29,37.03,37.51,37.71,37.77,37.76,37.74,37.79,37.85,37.8,37.78,37.68,37.45,37.31,37.2,36.81,36.15,35.69,35.62,35.64,35.5,35.35,35.4,35.93,36.72,37.25,37.47]
wt5_heartrate = [331.47,410.62,463.32,480.56,473.31,459.9,452.98,454.75,461.56,470.87,484.46,505.84,534.55,562.83,578.89,574.82,552.25,520.8,491.4,470.81,460.3,457.16,456.96,456.11,453.75,451.48,451.06,452.29,453.44,453.55,454.49,461.06,478.03,505.51,536.27,558.56,563.27,549.66,525.12,499.9,481.87,475.01,480.79,498.93,525.28,549.9,560.69,552.6,533.76,520.3,523.28,540.41,560.34,573.63,578.49,578.02,574.9,570.02,564.09,558.59,554.81,552.92,552.29,552.27,552.39,552.24,551.57,550.63,550.19,550.88,552.73,555.04,556.38,554.57,547.06,532.59,512.76,491.6,473.03,459.32,452.36,455.58,472.62,503.18,540.53,574.07,595.23,601.76,597.62,589.4,582.49,579.13,578.75,579.31,578.58,574.91,567.41,556.08,541.99,527.21,514.02,503.74,496.21,490.82,488.54,492.6,505.66,525.36,543.11,549.4,541.17,523.96,506.83,495.72,491.37,491.71,494.49,497.69,498.8,495.44,487.4,478.19,473.99,480.22,497.57,520.13,537.52,540.95,529.09,508.91,490.2,479.05,476.1,479.64,488.66,501.97,515.35,521.91,517.48,506.06,498.71,505.08,525.26,549.53,565.84,568.35,560.79,553.23,554.81,567.03,582.81,592.37,590.95,581.33,569.71,560.1,552.83,546.82,542.14,540.11,541.58,545.37,548.68,549.15,546.78,543.85,543.01,545.34,549.85,554.01,554.52,548.03,532.35,508.52,481.79,459.69,448.17,449.67,464.37,491.41,526.74,561.1,583.36,587.92,578.53,564.48,553.59,548.63,548.51,551.01,554.27,556.99,557.78,554.81,546.51,532.93,516.34,499.85,485.46,473.6,464.31,458.29,456.62,460.16,469.8,486.63,509.82,533.63,548.04,545.19,526.28,501.47,481.99,472.29,469.38,467.99,465.25,461.21,457.09,454.15,453.41,455.56,461.25,471.6,487.59,507.33,524.65,532.4,528.34,516.93,504.55,494.12,485.64,481.11,486.37,506.26,538.25,571.75,593.88,596.72,580.97,555.18,532.03,522.91,532.44,556.03,582.79,602.15,609.44,606.79,599.74,593.11,588.75,585.99,583.12,578.26,569.53,556.26,541.45,532.31,535.95,552.76,574.56,590.46,594.96,590.47,583.31,578.29,576.74,577.61,579.03,579.39,577.66,573.25,565.19,551.64,530.99,504.17,475.89,452.9,440.63,441.7,457.24,487.39,528.77,572.1,605.2,619.96,616.62]
heart=list(zip(wt5_time,wt5_heartrate))
temp=list(zip(wt5_time,wt5_temp))
list_plot(heart,color="red",axes_lables=["time","heart rate"])

verbose 0 (163: primitive.py, options) WARNING: Ignoring option 'axes_lables'=['time', 'heart rate'] verbose 0 (163: primitive.py, options) The allowed options for Point set defined by 289 point(s) are: alpha How transparent the point is. faceted If True color the edge of the point. (only for 2D plots) hue The color given as a hue. legend_color The color of the legend text legend_label The label for this item in the legend. marker the marker symbol for 2D plots only (see documentation of plot() for details) markeredgecolorthe color of the marker edge (only for 2D plots) rgbcolor The color as an RGB tuple. size How big the point is (i.e., area in points^2=(1/72 inch)^2). zorder The layer level in which to draw verbose 0 (163: primitive.py, options) WARNING: Ignoring option 'axes_lables'=['time', 'heart rate'] verbose 0 (163: primitive.py, options) The allowed options for Point set defined by 289 point(s) are: alpha How transparent the point is. faceted If True color the edge of the point. (only for 2D plots) hue The color given as a hue. legend_color The color of the legend text legend_label The label for this item in the legend. marker the marker symbol for 2D plots only (see documentation of plot() for details) markeredgecolorthe color of the marker edge (only for 2D plots) rgbcolor The color as an RGB tuple. size How big the point is (i.e., area in points^2=(1/72 inch)^2). zorder The layer level in which to draw verbose 0 (163: primitive.py, options) WARNING: Ignoring option 'axes_lables'=['time', 'heart rate'] verbose 0 (163: primitive.py, options) The allowed options for Point set defined by 289 point(s) are: alpha How transparent the point is. faceted If True color the edge of the point. (only for 2D plots) hue The color given as a hue. legend_color The color of the legend text legend_label The label for this item in the legend. marker the marker symbol for 2D plots only (see documentation of plot() for details) markeredgecolorthe color of the marker edge (only for 2D plots) rgbcolor The color as an RGB tuple. size How big the point is (i.e., area in points^2=(1/72 inch)^2). zorder The layer level in which to draw
In [21]:
list_plot(temp,color="blue",axes_labels=["time","temperature"])

In [22]:
#both of the graphs oscillate, but the minimum and maximum values are diferent.

In [25]:
tempheart=list(zip(wt5_temp,wt5_heartrate))
list_plot(tempheart,plotjoined=true, axes_labels=["temperature","heart rate"])


### For loops

Suppose you wanted to print out a series of sentences listing your favorite foods. You might use the print command and write:

print("Pizza is one of my favorite foods.")
print("Chocolate is one of my favorite foods.")
print("Green curry is one of my favorite foods.")


This works, but it’s rather tedious, especially if you like many kinds of food. A shortcut would be useful.

Looking at the example, you can see that the print command and the string " is one of my favorite foods." are the same in every line. The only thing that changes is the name of the food. It would be convenient if we could just make a list of the foods and insert them into the code one at a time.

We can do this using something called a for loop. One way to handle the foods example with a for loop is the following:

favorites = ["Pizza", "Chocolate", "Green curry"]
for food in favorites:
print(food + " is one of my favorite foods.")


In this example, food is a variable that takes on the value "Pizza" the first time the computer executes the statement print food + " is one of my favorite foods.", "Chocolate" the second time and "Green curry" the third time.

Exercise 19. Print out sentences listing five of your favorite books, songs or movies using a for loop.
In [27]:
favorites=["Up","Shrek","Meet the Robinsons"]
for movies in favorites:
print(movies + " is one of my favorite movies")

Up is one of my favorite movies Shrek is one of my favorite movies Meet the Robinsons is one of my favorite movies

More generally, a for loop in SageMath (or Python) has the form:

for var in list:
loop body


The loop body must be indented. After the loop body, go back to your previous level of indentation.

Example 4. A string is similar in most ways to a list. This loop will print each character in the word “dynamics” on a separate line.

>>for char in "dynamics":
>> print(char)
d
y
n
a
m
i
c
s


As you can see, the variable given immediately after the word for takes on the value of each list element in turn. First char was "d", then it was "y", then "n", and so on. This is the key to how SageMath for loops work. The body of the loop is executed for each element in the list. The body stays the same, while the list element changes. When writing loops, think about what should stay the same and what should change.

Example 5. The following loop computes the base-10 logarithm of 10, 100, and 1000 in SageMath:

>>for val in [10, 100, 1000]:
>> print(log(val, 10))
1
2
3

Exercise 20.Use a for loop to print your name vertically.

Exercise 21. Use a for loop to square the numbers 15, 27, 39 and 84.

225
729
1521
7056

In [ ]:


In [28]:
for char in "Makayla":
print(char)

M a k a y l a
In [29]:
for val in [15,27,39,84]:
print(val^2)

225 729 1521 7056

## Things to Do with Lists and Loops

### Using loops to make lists

In the previous exercises, you used loops to output values. Often, it is useful to store these values in a list.

To start, you’ll need to create a list with no elements. (Think of this as tearing out a piece of paper and titling it “Groceries” when making a shopping list.) To make such an empty list, enter listname = []. Then, use listname.append() to add computed values to your list.

Example 6. This code makes a list of the first ten multiples of 2.

>>mult2 = []         #Set up empty list
>>for n in [1,2,3,4,5,6,7,8,9,10]:
>> mult2.append(2*n) #Compute the n’th multiple of 2 and append to list
>>mult2              #Display the list
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Exercise 22. Make a list containing the first five multiples of 3.
[3, 6, 9, 12, 15]

Exercise 23. Write a loop that makes a list of the squares of the numbers 0.1, 0.2, $\dots$, 0.7. Then, plot your list.

[0.0100000000000000, 0.0400000000000000, 0.0900000000000000, 0.160000000000000, 0.250000000000000, 0.360000000000000, 0.490000000000000]

Exercise 24. Create a function and apply it to the numbers 0 through 5, inclusive. Plot the list of resulting values.

In [32]:
mult3=[]
for n in [1,2,3,4,5]:
mult3.append(3*n)
mult3

[3, 6, 9, 12, 15]
In [33]:
square=[]
for n in [0.1,0.2,0.3,0.4,0.5,0.6,0.7]:
square.append(n^2)
square
list_plot(square)

In [34]:
func=[]
for n in [0,1,2,3,4,5]:
func.append(2*n+6)
func

[6, 8, 10, 12, 14, 16]

We can use loops to process data.

Exercise 25. The time in wt5_time is measured in hours. Create another list in which it is given in minutes.

Exercise 26. Convert the temperatures in wt5_temp from Celsius to Fahrenheit. (The formula is $F = (9/5) C + 32$.)

Exercise 27. Plot a time series of your transformed data.

Exercise 28. Plot a trajectory of the transformed temperature data and the original heart rate data.

In [37]:
minutes=[]
for x in wt5_temp:
minutes.append(x/60.0)

In [38]:
cel = []
for x in wt5_temp:
cel.append((9/5)*x+32)

timeseries=list(zip(minutes,cel))
list_plot(timeseries)

In [40]:
trajectory=list(zip(cel,wt5_heartrate))
list_plot(trajectory, plotjoined=true)


## Animations

When investigating functions and models, it can be useful to animate their response to changes in parameters. Sage’s animate function allows us to easily produce such animations.

Animations are created by showing a series of still images one after the other, fast enough to create the illusion of motion. The animate function takes a list of plots as input and animates it.

Example 7. The following code shows how a change in the slope of a line affects the line’s appearance.

plots = []       #Set up empty list to hold plots
slopes = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] #Make a list of slopes
for m in slopes: #For each m in slope, create plot, add to list
p=plot(m*x, (x,-10,10))
plots.append(p)
a=animate(plots) #Create the animation
show(a)          #Necessary to display the animation


Try this code now. The show command is necessary to view the animation; it can also be used with other graphics.

Oops! The code produces an animation all right, but the animation is useless because it’s the axes, not the line, that move. To stop this from happening, we can specify maximum and minimum values for $y$, fixing the $y$-axis in place.

Example 8. Fixing the y-axis in an animation

plots = []        #Set up empty list to hold plots
slopes = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] #Make a list of slopes
for m in slopes:  #For each m in slope, create plot, add to list
p=plot(m*x, (x,-10,10), ymin=-50, ymax=50)
plots.append(p)
a=animate(plots)  #Create the animation
show(a)           #Necessary to display the animation


This code produces a useful animated plot.

Exercise 29. Change the animation in Example 8 to make the line green rather than blue.

Exercise 30. Change the previous animation to make the slope range from -3 to 3 in steps of 0.5.

Exercise 31. Rewrite the animation in Exercise 29 so that the slope of the line plotted is always 1 but the $y$-intercept ranges between -5 and 5.

In [55]:
plots = []
slopes = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
for m in slopes:
p=plot(m*x, (x,-10,10), ymin=-50, ymax=50,color="green")
plots.append(p)
a=animate(plots)
show(a)

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-55-631343fbda20> in <module>() 2 slopes = [-Integer(5), -Integer(4), -Integer(3), -Integer(2), -Integer(1), Integer(0), Integer(1), Integer(2), Integer(3), Integer(4), Integer(5)] 3 for m in slopes: ----> 4 p=plot(m*x, (x,-Integer(10),Integer(10)), ymin=-Integer(50), ymax=Integer(50),color="green") 5 plots.append(p) 6 a=animate(plots) TypeError: 'list' object is not callable 
In [56]:
plots = []
slopes = [-3,-2.5,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,2.5,3]
for m in slopes:
p=plot(m*x, (x,-3,3), ymin=-50, ymax=50, color="green")
plots.append(p)
a=animate(plots)
show(a)

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-56-6c2d8b8bf917> in <module>() 2 slopes = [-Integer(3),-RealNumber('2.5'),-Integer(2),-RealNumber('1.5'),-Integer(1),-RealNumber('0.5'),Integer(0),RealNumber('0.5'),Integer(1),RealNumber('1.5'),Integer(2),RealNumber('2.5'),Integer(3)] 3 for m in slopes: ----> 4 p=plot(m*x, (x,-Integer(3),Integer(3)), ymin=-Integer(50), ymax=Integer(50), color="green") 5 plots.append(p) 6 a=animate(plots) TypeError: 'list' object is not callable 
In [59]:
plots = []
yint = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
for m in slopes:
p=plot(1*x+b, (x,-10,10), ymin=-50, ymax=50)
plots.append(p)
a=animate(plots)
show(a)

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-46d4786cfc9d> in <module>() 2 yint = [-Integer(5),-Integer(4),-Integer(3),-Integer(2),-Integer(1),Integer(0),Integer(1),Integer(2),Integer(3),Integer(4),Integer(5)] 3 for m in slopes: ----> 4 p=plot(Integer(1)*x+b, (x,-Integer(10),Integer(10)), ymin=-Integer(50), ymax=Integer(50)) 5 plots.append(p) 6 a=animate(plots) TypeError: 'list' object is not callable 
In [ ]: