8 CHAPTER 1.COMPUTERS AND PROGRAMS Typing the first line import chaos tells the Python interpreter to load the chaos module from the file chaos.py into main memory.Notice that I did not include the py extension on the import line:Python assumes the module will have a py extension. As Python imports the module file,each line executes.It's just as if we had typed them one-by-one at the interactive Python prompt.The def in the module causes Python to create the main function.When Python encounters the last line of the module,the ma in function is invoked,thus running our program.The running program asks the user to enter a number between 0 and 1(in this case,I typed"25")and then prints out a series of 10 numbers. When you first import a module file in this way,Python creates a companion file with a.pyc extension. In this example,Python creates another file on the disk called chaos.pyc.This is an intermediate file used by the Python interpreter.Technically,Python uses a hybrid compiling/interpreting process.The Python source in the module file is compiled into more primitive instructions called byte code.This byte code (the pyc)file is then interpreted.Having a.pyc file available makes importing a module faster the second time around.However,you may delete the byte code files if you wish to save disk space;Python will automatically re-create them as needed. A module only needs to be imported into a session once.After the module has been loaded,we can run the program again by asking Python to execute the main command.We do this by using a special dot notation. Typing chaos.main (tells Python to invoke the main function in the chaos module.Continuing with our example,here is how it looks when we rerun the program with.26 as the input. >>chaos.main() Enter a number between 0 and 1:.26 0.75036 0.73054749456 0.767706625733 0.6954993339 0.825942040734 0.560670965721 0.960644232282 0.147446875935 0.490254549376 0.974629602149 >>> 1.7 Inside a Python Program The output from the chaos program may not look very exciting,but it illustrates a very interesting phe- nomenon known to physicists and mathematicians.Let's take a look at this program line by line and see what it does.Don't worry about understanding every detail right away;we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the character: File:chaos.py A simple program illustrating chaotic behavior. These lines are called comments.They are intended for human readers of the program and are ignored by Python.The Python interpreter always skips any text from the pound sign(#)through the end of a line. The next line of the program begins the definition of a function called main. def main(): Strictly speaking,it would not be necessary to create a main function.Since the lines of a module are executed as they are loaded,we could have written our program without this definition.That is,the module could have looked like this:
8 CHAPTER 1. COMPUTERS AND PROGRAMS Typing the first line import chaos tells the Python interpreter to load the chaos module from the file chaos.py into main memory. Notice that I did not include the .py extension on the import line; Python assumes the module will have a .py extension. As Python imports the module file, each line executes. It’s just as if we had typed them one-by-one at the interactive Python prompt. The def in the module causes Python to create the main function. When Python encounters the last line of the module, the main function is invoked, thus running our program. The running program asks the user to enter a number between 0 and 1 (in this case, I typed “.25”) and then prints out a series of 10 numbers. When you first import a module file in this way, Python creates a companion file with a .pyc extension. In this example, Python creates another file on the disk called chaos.pyc. This is an intermediate file used by the Python interpreter. Technically, Python uses a hybrid compiling/interpreting process. The Python source in the module file is compiled into more primitive instructions called byte code. This byte code (the .pyc) file is then interpreted. Having a .pyc file available makes importing a module faster the second time around. However, you may delete the byte code files if you wish to save disk space; Python will automatically re-create them as needed. A module only needsto be imported into a session once. After the module has been loaded, we can run the program again by asking Python to execute the main command. We do this by using a special dot notation. Typing chaos.main() tells Python to invoke the main function in the chaos module. Continuing with our example, here is how it looks when we rerun the program with 26 as the input. >>> chaos.main() Enter a number between 0 and 1: .26 0.75036 0.73054749456 0.767706625733 0.6954993339 0.825942040734 0.560670965721 0.960644232282 0.147446875935 0.490254549376 0.974629602149 >>> 1.7 Inside a Python Program The output from the chaos program may not look very exciting, but it illustrates a very interesting phenomenon known to physicists and mathematicians. Let’s take a look at this program line by line and see what it does. Don’t worry about understanding every detail right away; we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the # character: # File: chaos.py # A simple program illustrating chaotic behavior. These lines are called comments. They are intended for human readers of the program and are ignored by Python. The Python interpreter always skips any text from the pound sign (#) through the end of a line. The next line of the program begins the definition of a function called main. def main(): Strictly speaking, it would not be necessary to create a main function. Since the lines of a module are executed as they are loaded, we could have written our program without this definition. That is, the module could have looked like this:
1.7.INSIDE A PYTHON PROGRAM 9 File:chaos.py A simple program illustrating chaotic behavior. print "This program illustrates a chaotic function" x=input("Enter a number between 0 and 1:" for i in range(10): x=3.9*×*(1-x) print x This version is a bit shorter,but it is customary to place the instructions that comprise a program inside of a function called main.One immediate benefit of this approach was illustrated above;it allows us to(re)run the program by simply invoking chaos.main ()We don't have to reload the module from the file in order to run it again,which would be necessary in the main-less case. The first line inside of main is really the beginning of our program print "This program illustrates a chaotic function" This line causes Python to print a message introducing the program when it runs. Take a look at the next line of the program. x input ("Enter a number between 0 and 1:" Here x is an example of a variable.A variable is used to give a name to a value so that we can refer to it at other points in the program.The entire line is an input statement.When Python gets to this statement,it displays the quoted message Enter a number between 0 and 1:and then pauses,waiting for the user to type something on the keyboard and press the <Enter>key.The value that the user types is then stored as the variable x.In the first example shown above,the user entered.25.which becomes the value of X. The next statement is an example of a loop. for i in range(10): A loop is a device that tells Python to do the same thing over and over again.This particular loop says to do something 10 times.The lines indented underneath the loop heading are the statements that are done 10 times.These form the body of the loop. ×=3.9*x*(1-) print x The effect of the loop is exactly the same as if we had written the body of the loop 10 times: ×=3.9*×*(1-) print x ×=3.9*x*(1-) print x ×=3.9*x*(1-) print x x=3.9*x*(1-x) print x ×=3.9*x*(1-) print x ×=3.9*×*(1-) print x ×=3.9*8*(1-) print x x=3.9*X*(1-x) print x ×=3.9*x*(1-x)
1.7. INSIDE A PYTHON PROGRAM 9 # File: chaos.py # A simple program illustrating chaotic behavior. print "This program illustrates a chaotic function" x = input("Enter a number between 0 and 1: ") for i in range(10): x = 3.9 * x * (1 - x) print x This version is a bit shorter, but it is customary to place the instructions that comprise a program inside of a function called main. One immediate benefit of this approach was illustrated above; it allows us to (re)run the program by simply invoking chaos.main(). We don’t have to reload the module from the file in order to run it again, which would be necessary in the main-less case. The first line inside of main is really the beginning of our program. print "This program illustrates a chaotic function" This line causes Python to print a message introducing the program when it runs. Take a look at the next line of the program. x = input("Enter a number between 0 and 1: ") Here x is an example of a variable. A variable is used to give a name to a value so that we can refer to it at other points in the program. The entire line is an input statement. When Python gets to this statement, it displays the quoted message Enter a number between 0 and 1: and then pauses, waiting for the user to type something on the keyboard and press the <Enter> key. The value that the user types is then stored as the variable x. In the first example shown above, the user entered .25, which becomes the value of x. The next statement is an example of a loop. for i in range(10): A loop is a device that tells Python to do the same thing over and over again. This particular loop says to do something 10 times. The lines indented underneath the loop heading are the statements that are done 10 times. These form the body of the loop. x = 3.9 * x * (1 - x) print x The effect of the loop is exactly the same as if we had written the body of the loop 10 times: x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x) print x x = 3.9 * x * (1 - x)
10 CHAPTER 1.COMPUTERS AND PROGRAMS print x ×=3.9*x*(1-) print x Obviously using the loop instead saves the programmer a lot of trouble. But what exactly do these statements do?The first one performs a calculation. x=3.9*×*(1-) This is called an assignment statement.The part on the right side of the =is a mathematical expression. Python uses the character to indicate multiplication.Recall that the value of x is 0.25(from the input statement).The computed value is 3.9(0.25)(1-0.25)or 0.73125.Once the value on the righthand side is computed,it is stored back(or assigned)into the variable that appears on the lefthand side of the =in this case x.The new value of x(0.73125)replaces the old value (0.25). The second line in the loop body is a type of statement we have encountered before,a print statement. print x When Python executes this statement the current value of x is displayed on the screen.So,the first number of output is 0.73125. Remember the loop executes 10 times.After printing the value of x,the two statements of the loop are executed again x=3.9*x*(1-x) print x Of course,now x has the value 0.73125,so the formula computes a new value of x as 3.9(0.73125)(1- 0.73125).which is0.76644140625. Can you see how the current value ofx is used to compute a new value each time around the loop?That's where the numbers in the example run came from.You might try working through the steps of the program yourself for a different input value(say 0.5).Then run the program using Python and see how well you did impersonating a computer. 1.8 Chaos and Computers I said above that the chaos program illustrates an interesting phenomenon.What could be interesting about a screen full of numbers?If you try out the program for yourself,you'll find that,no matter what number you start with,the results are always similar:the program spits back 10 seemingly random numbers between 0 and 1.As the program runs,the value ofx seems to jump around,well,chaotically. The function computed by this program has the general form:k(x)(1-x),where k in this case is 3.9. This is called a logistic function.It models certain kinds of unstable electronic circuits and is also sometimes used to predict population under limiting conditions.Repeated application of the logistic function can pro- duce chaos.Although our program has a well defined underlying behavior,the output seems unpredictable. An interesting property of chaotic functions is that very small differences in the initial value can lead to large differences in the result as the formula is repeatedly applied.You can see this in the chaos program by entering numbers that differ by only a small amount.Here is the output from a modified program that shows the results for initial values of 0.25 and 0.26 side by side. input 0.25 0.26 0.731250 0.750360 0.766441 0.730547 0.698135 0.767707 0.821896 0.695499 0.570894 0.825942 0.955399 0.560671
10 CHAPTER 1. COMPUTERS AND PROGRAMS print x x = 3.9 * x * (1 - x) print x Obviously using the loop instead saves the programmer a lot of trouble. But what exactly do these statements do? The first one performs a calculation. x = 3.9 * x * (1 - x) This is called an assignment statement. The part on the right side of the = is a mathematical expression. Python uses the * character to indicate multiplication. Recall that the value of x is 0 25 (from the input statement). The computed value is 3 9 0 25✁ 1 ✂ 0 25✁ or 0 73125. Once the value on the righthand side is computed, it is stored back (or assigned) into the variable that appears on the lefthand side of the =, in this case x. The new value of x (0 73125) replaces the old value (0 25). The second line in the loop body is a type of statement we have encountered before, a print statement. print x When Python executes this statement the current value of x is displayed on the screen. So, the first number of output is 0.73125. Remember the loop executes 10 times. After printing the value of x, the two statements of the loop are executed again. x = 3.9 * x * (1 - x) print x Of course, now x has the value 0 73125, so the formula computes a new value of x as 3 9 0 73125 ✁ 1 ✂ 0 73125✁ , which is 0 76644140625. Can you see how the current value of x is used to compute a new value each time around the loop? That’s where the numbers in the example run came from. You might try working through the steps of the program yourself for a different input value (say 0 5). Then run the program using Python and see how well you did impersonating a computer. 1.8 Chaos and Computers I said above that the chaos program illustrates an interesting phenomenon. What could be interesting about a screen full of numbers? If you try out the program for yourself, you’ll find that, no matter what number you start with, the results are always similar: the program spits back 10 seemingly random numbers between 0 and 1. As the program runs, the value of x seems to jump around, well, chaotically. The function computed by this program has the general form: k x ✁ 1 ✂ x✁ , where k in this case is 3.9. This is called a logistic function. It models certain kinds of unstable electronic circuits and is also sometimes used to predict population under limiting conditions. Repeated application of the logistic function can produce chaos. Although our program has a well defined underlying behavior, the output seems unpredictable. An interesting property of chaotic functions is that very small differences in the initial value can lead to large differences in the result as the formula is repeatedly applied. You can see this in the chaos program by entering numbers that differ by only a small amount. Here is the output from a modified program that shows the results for initial values of 0 25 and 0 26 side by side. input 0.25 0.26 --------------------------- 0.731250 0.750360 0.766441 0.730547 0.698135 0.767707 0.821896 0.695499 0.570894 0.825942 0.955399 0.560671
1.9.EXERCISES 11 0.166187 0.960644 0.540418 0.147447 0.968629 0.490255 0.118509 0.974630 With very similar starting values,the outputs stay similar for a few iterations,but then differ markedly.By about the fifth iteration,there no longer seems to be any relationship between the two models. These two features of our chaos program,apparent unpredictability and extreme sensitivity to initial values,are the hallmarks of chaotic behavior.Chaos has important implications for computer science.It turns out that many phenomena in the real world that we might like to model and predict with our computers exhibit just this kind of chaotic behavior.You may have heard of the so-called butterfly effect.Computer models that are used to simulate and predict weather patterns are so sensitive that the effect of a single butterfly flapping its wings in New Jersey might make the difference of whether or not rain is predicted in Peoria. It's very possible that even with perfect computer modeling,we might never be able to measure existing weather conditions accurately enough to predict weather more than a few days in advance.The measurements simply can't be precise enough to make the predictions accurate over a longer time frame. As you can see,this small program has a valuable lesson to teach users of computers.As amazing as computers are,the results that they give us are only as useful as the mathematical models on which the programs are based.Computers can give incorrect results because of errors in programs,but even correct programs may produce erroneous results if the models are wrong or the initial inputs are not accurate enough. 1.9 Exercises 1.Compare and contrast the following pairs of concepts from the chapter. (a)Hardware vs.Software (b)Algorithm vs.Program (c)Programming Language vs.Natural Language (d)High-Level Language vs.Machine Language (e)Interpreter vs.Compiler (f)Syntax vs.Semantics 2.List and explain in your own words the role of each of the five basic functional units of a computer depicted in Figure 1.1. 3.Write a detailed algorithm for making a peanut butter and jelly sandwich(or some other simple every- day activity) 4.As you will learn in a later chapter,many of the numbers stored in a computer are not exact values,but rather close approximations.For example,the value 0.1,might be stored as 0.10000000000000000555. Usually,such small differences are not a problem;however,given what you have learned about chaotic behavior in Chapter 1,you should realize the need for caution in certain situations.Can you think of examples where this might be a problem?Explain. 5.Trace through the Chaos program from Section 1.6 by hand using 0 15 as the input value.Show the sequence of output that results. 6.Enter and run the Chaos program from Section 1.6 using whatever Python implementation you have available.Try it out with various values of input to see that it functions as described in the chapter. 7.Modify the Chaos program from Section 1.6 using 2.0 in place of 3.9 as the multiplier in the logistic function.Your modified line of code should look like this:
1.9. EXERCISES 11 0.166187 0.960644 0.540418 0.147447 0.968629 0.490255 0.118509 0.974630 With very similar starting values, the outputs stay similar for a few iterations, but then differ markedly. By about the fifth iteration, there no longer seems to be any relationship between the two models. These two features of our chaos program, apparent unpredictability and extreme sensitivity to initial values, are the hallmarks of chaotic behavior. Chaos has important implications for computer science. It turns out that many phenomena in the real world that we might like to model and predict with our computers exhibit just this kind of chaotic behavior. You may have heard of the so-called butterfly effect. Computer models that are used to simulate and predict weather patterns are so sensitive that the effect of a single butterfly flapping its wings in New Jersey might make the difference of whether or not rain is predicted in Peoria. It’s very possible that even with perfect computer modeling, we might never be able to measure existing weather conditions accurately enough to predict weather more than a few days in advance. The measurements simply can’t be precise enough to make the predictions accurate over a longer time frame. As you can see, this small program has a valuable lesson to teach users of computers. As amazing as computers are, the results that they give us are only as useful as the mathematical models on which the programs are based. Computers can give incorrect results because of errors in programs, but even correct programs may produce erroneousresults if the models are wrong or the initial inputs are not accurate enough. 1.9 Exercises 1. Compare and contrast the following pairs of concepts from the chapter. (a) Hardware vs. Software (b) Algorithm vs. Program (c) Programming Language vs. Natural Language (d) High-Level Language vs. Machine Language (e) Interpreter vs. Compiler (f) Syntax vs. Semantics 2. List and explain in your own words the role of each of the five basic functional units of a computer depicted in Figure 1.1. 3. Write a detailed algorithm for making a peanut butter and jelly sandwich (or some other simple everyday activity). 4. As you will learn in a later chapter, many of the numbers stored in a computer are not exact values, but rather close approximations. For example, the value 0.1, might be stored as 0.10000000000000000555. Usually, such small differences are not a problem; however, given what you have learned about chaotic behavior in Chapter 1, you should realize the need for caution in certain situations. Can you think of examples where this might be a problem? Explain. 5. Trace through the Chaos program from Section 1.6 by hand using 0 15 as the input value. Show the sequence of output that results. 6. Enter and run the Chaos program from Section 1.6 using whatever Python implementation you have available. Try it out with various values of input to see that it functions as described in the chapter. 7. Modify the Chaos program from Section 1.6 using 2.0 in place of 3.9 as the multiplier in the logistic function. Your modified line of code should look like this:
12 CHAPTER 1.COMPUTERS AND PROGRAMS ×=2.0*8*(1-) Run the program for various input values and compare the results to those obtained from the original program.Write a short paragraph describing any differences that you notice in the behavior of the two versions. 8.Modify the Chaos program from Section 1.6 so that it prints out 20 values instead of 10 9.(Advanced)Modify the Chaos program so that it accepts two inputs and then prints a table with two columns similar to the one shown in Section 1.8.(Note:You will probably not be able to get the columns to line up as nicely as those in the example.Chapter 4 discusses how to print numbers with a fixed number of decimal places
12 CHAPTER 1. COMPUTERS AND PROGRAMS x = 2.0 * x * (1 - x) Run the program for various input values and compare the results to those obtained from the original program. Write a short paragraph describing any differences that you notice in the behavior of the two versions. 8. Modify the Chaos program from Section 1.6 so that it prints out 20 values instead of 10. 9. (Advanced) Modify the Chaos program so that it accepts two inputs and then prints a table with two columns similar to the one shown in Section 1.8. (Note: You will probably not be able to get the columns to line up as nicely as those in the example. Chapter 4 discusses how to print numbers with a fixed number of decimal places.)