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 025(from the input statement).The computed value is 39025)1-025)or 093125.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 (093125)replaces the old value (025). 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 3125,so the formula computes a new value ofx as33125) 033125).which is036644140625. 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 05).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:kx)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 of025 and 026 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.)
Chapter 2 Writing Simple Programs As you saw in the previous chapter,it is easy to run programs that have already been written.The hard part is actually coming up with the program in the first place.Computers are very literal,and they must be told what to do right down to the last detail.Writing large programs is a daunting task.It would be almost impossible without a systematic approach. 2.1 The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase.In a nutshell,here's what you should do. Formulate Requirements Figure out exactly what the problem to be solved is.Try to understand as much as possible about it.Until you really know what the problem is,you cannot begin to solve it. Determine Specifications Describe exactly what your program will do.At this point,you should not worry about how your program will work,but rather with deciding exactly what it will accomplish.For simple programs this involves carefully describing what the inputs and outputs of the program will be and how they relate to each other. Create a Design Formulate the overall structure of the program.This is where the how of the program gets worked out.The main task is to design the algorithm(s)that will meet the specifications. Implement the Design Translate the design into a computer language and put it into the computer.In this book,we will be implementing our algorithms as Python programs. Test/Debug the Program Try out your program and see if it works as expected.If there are any errors(often called bugs),then you should go back and fix them.The process of locating and fixing errors is called debugging a program. Maintain the Program Continue developing the program in response to the needs of your users.Most programs are never really finished;they keep evolving over years of use. 2.2 Example Program:Temperature Converter Let's go through the steps of the software development process with a simple real-world example.Suzie Programmer has a problem.Suzie is an American computer science student spending a year studying in Europe.She has no problems with language,as she is fluent in many languages(including Python).Her problem is that she has a hard time figuring out the temperature in the morning so that she knows how to dress for the day.Suzie listens to the weather report each morning,but the temperatures are given in degrees Celsius,and she is used to Fahrenheit. 13
Chapter 2 Writing Simple Programs As you saw in the previous chapter, it is easy to run programs that have already been written. The hard part is actually coming up with the program in the first place. Computers are very literal, and they must be told what to do right down to the last detail. Writing large programs is a daunting task. It would be almost impossible without a systematic approach. 2.1 The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase. In a nutshell, here’s what you should do. Formulate Requirements Figure out exactly what the problem to be solved is. Try to understand as much as possible about it. Until you really know what the problem is, you cannot begin to solve it. Determine Specifications Describe exactly what your program will do. At this point, you should not worry about how your program will work, but rather with deciding exactly what it will accomplish. For simple programs this involves carefully describing what the inputs and outputs of the program will be and how they relate to each other. Create a Design Formulate the overall structure of the program. This is where the how of the program gets worked out. The main task is to design the algorithm(s) that will meet the specifications. Implement the Design Translate the design into a computer language and put it into the computer. In this book, we will be implementing our algorithms as Python programs. Test/Debug the Program Try out your program and see if it works as expected. If there are any errors (often called bugs), then you should go back and fix them. The process of locating and fixing errors is called debugging a program. Maintain the Program Continue developing the program in response to the needs of your users. Most programs are never really finished; they keep evolving over years of use. 2.2 Example Program: Temperature Converter Let’s go through the steps of the software development process with a simple real-world example. Suzie Programmer has a problem. Suzie is an American computer science student spending a year studying in Europe. She has no problems with language, as she is fluent in many languages (including Python). Her problem is that she has a hard time figuring out the temperature in the morning so that she knows how to dress for the day. Suzie listens to the weather report each morning, but the temperatures are given in degrees Celsius, and she is used to Fahrenheit. 13