v1.23 - 02/17/08 SAGE For Newbies 1/150

SAGE For Newbies

by Ted Kosan

Copyright © 2007 by Ted Kosan

This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ v1.23 - 02/17/08 SAGE For Newbies 2/150

Table of Contents

1 Preface...... 8 1.1 Dedication...... 8 1.1 Acknowledgments...... 8 1.2 Support Group...... 8

2 Introduction...... 9 2.1 What Is A Mathematics Computing Environment?...... 9 2.2 What Is SAGE?...... 10 2.3 Accessing SAGE As A Web Service...... 12 2.3.1 Accessing SAGE As A Web Service Using Scenario 1...... 13 2.4 Entering Source Code Into A SAGE Cell...... 16

3 SAGE Programming Fundamentals...... 20 3.1 Objects, Values, And Expressions...... 20 3.2 Operators...... 21 3.3 Operator Precedence...... 22 3.4 Changing The Order Of Operations In An Expression...... 23 3.5 Variables...... 23 3.6 Statements...... 25 3.6.1 The print Statement...... 25 3.7 Strings...... 27 3.8 Comments...... 27 3.9 Conditional Operators...... 28 3.10 Making Decisions With The if Statement...... 30 3.11 The and, or, And not Boolean Operators...... 32 3.12 Looping With The while Statement...... 34 3.13 Long-Running Loops, Infinite Loops, And Interrupting Execution...... 36 3.14 Inserting And Deleting Worksheet Cells...... 37 3.15 Introduction To More Advanced Object Types...... 37 3.15.1 Rational Numbers...... 37 3.15.2 Real Numbers...... 38 3.15.3 Objects That Hold Sequences Of Other Objects: Lists And Tuples...39 3.15.3.1 Tuple Packing And Unpacking...... 40 3.16 Using while Loops With Lists And Tuples...... 41 3.17 The in Operator...... 42 3.18 Looping With The for Statement...... 42 3.19 Functions...... 43 3.20 Functions Are Defined Using the def Statement...... 43 3.21 A Subset Of Functions Included In SAGE...... 45 3.22 Obtaining Information On SAGE Functions...... 52 3.23 Information Is Also Available On User-Entered Functions...... 53 v1.23 - 02/17/08 SAGE For Newbies 3/150

3.24 Examples Which Use Functions Included With SAGE...... 54 3.25 Using srange() And zip() With The for Statement...... 55 3.26 List Comprehensions...... 56

4 Object Oriented Programming...... 58 4.1 Object Oriented Mind Re-wiring...... 58 4.2 Attributes And Behaviors...... 58 4.3 Classes (Blueprints That Are Used To Create Objects)...... 59 4.4 Object Oriented Programs Create And Destroy Objects As Needed...... 59 4.5 Object Oriented Program Example...... 60 4.5.1 Hellos Object Oriented Program Example (No Comments)...... 60 4.5.2 Hellos Object Oriented Program Example (With Comments)...... 61 4.6 SAGE Classes And Objects...... 65 4.7 Obtaining Information On SAGE Objects...... 65 4.8 The List Object's Methods...... 67 4.9 Extending Classes With Inheritence...... 68 4.10 The object Class, The dir() Function, And Built-in Methods...... 70 4.11 The Inheritance Hierarchy Of The sage.rings.integer.Integer Class...... 71 4.12 The "Is A" Relationship...... 73 4.13 Confused?...... 73

5 Miscellaneous Topics...... 74 5.1 Referencing The Result Of The Previous Operation...... 74 5.2 Exceptions...... 74 5.3 Obtaining Numeric Results...... 75 5.4 Style Guide For Expressions...... 76 5.5 Built-in Constants...... 76 5.6 Roots...... 78 5.7 Symbolic Variables...... 78 5.8 Symbolic Expressions...... 79 5.9 Expanding And Factoring...... 80 5.10 Miscellaneous Symbolic Expression Examples...... 81 5.11 Passing Values To Symbolic Expressions...... 81 5.12 Symbolic Equations and The solve() Function...... 82 5.13 Symbolic Mathematical Functions...... 83 5.14 Finding Roots Graphically And Numerically With The find_root() Method ...... 84 5.15 Displaying Mathematical Objects In Traditional Form...... 85 5.15.1 LaTeX Is Used To Display Objects In Traditional Mathematics Form ...... 86 5.16 Sets...... 86

6 2D Plotting...... 88 6.1 The plot() And show() Functions...... 88 6.1.1 Combining Plots And Changing The Plotting Color...... 90 v1.23 - 02/17/08 SAGE For Newbies 4/150

6.1.2 Combining Graphics With A Graphics Object...... 91 6.2 Advanced Plotting With matplotlib...... 92 6.2.1 Plotting Data From Lists With Grid Lines And Axes Labels...... 93 6.2.2 Plotting With A Logarithmic Y Axis...... 93 6.2.3 Two Plots With Labels Inside Of The Plot...... 94

7 SAGE Usage Styles...... 96 7.1 The Speed Usage Style...... 96 7.2 The OpenOffice Presentation Usage Style...... 96

8 High School Math Problems (most of the problems are still in development)...... 97 8.1 Pre-Algebra...... 97 8.1.1 Equations...... 97 8.1.2 Expressions...... 97 8.1.3 Geometry...... 97 8.1.4 Inequalities...... 97 8.1.5 Linear Functions...... 97 8.1.6 Measurement...... 97 8.1.7 Nonlinear Functions...... 97 8.1.8 Number Sense And Operations...... 98 8.1.8.1 Express an integer fraction in lowest terms...... 98 8.1.9 Polynomial Functions...... 99 8.2 Algebra...... 99 8.2.1 Absolute Value Functions...... 99 8.2.2 Complex Numbers...... 99 8.2.3 Composite Functions...... 99 8.2.4 Conics...... 99 8.2.5 Data Analysis...... 99 9 Discrete Mathematics: Elementary Number And Graph Theory ...... 100 9.1.1 Equations...... 100 9.1.1.1 Express a symbolic fraction in lowest terms...... 100 9.1.1.2 Determine the product of two symbolic fractions...... 102 9.1.1.3 Solve a linear equation for x...... 102 9.1.1.4 Solve a linear equation which has fractions...... 103 9.1.2 Exponential Functions...... 105 9.1.3 Exponents...... 105 9.1.4 Expressions...... 105 9.1.5 Inequalities...... 105 9.1.6 Inverse Functions...... 105 9.1.7 Linear Equations And Functions...... 106 9.1.8 Linear Programming...... 106 9.1.9 Logarithmic Functions...... 106 9.1.10 Logistic Functions...... 106 9.1.11 Matrices...... 106 9.1.12 Parametric Equations...... 106 v1.23 - 02/17/08 SAGE For Newbies 5/150

9.1.13 Piecewise Functions...... 106 9.1.14 Polynomial Functions...... 106 9.1.15 Power Functions...... 107 9.1.16 Quadratic Functions...... 107 9.1.17 Radical Functions...... 107 9.1.18 Rational Functions...... 107 9.1.19 Sequences...... 107 9.1.20 Series...... 107 9.1.21 Systems of Equations...... 107 9.1.22 Transformations...... 107 9.1.23 Trigonometric Functions...... 107 9.2 Precalculus And Trigonometry...... 108 9.2.1 Binomial Theorem...... 108 9.2.2 Complex Numbers...... 108 9.2.3 Composite Functions...... 108 9.2.4 Conics...... 108 9.2.5 Data Analysis...... 108 10 Discrete Mathematics: Elementary Number And Graph Theory ...... 108 10.1.1 Equations...... 108 10.1.2 Exponential Functions...... 109 10.1.3 Inverse Functions...... 109 10.1.4 Logarithmic Functions...... 109 10.1.5 Logistic Functions...... 109 10.1.6 Matrices And Matrix Algebra...... 109 10.1.7 Mathematical Analysis...... 109 10.1.8 Parametric Equations...... 109 10.1.9 Piecewise Functions...... 109 10.1.10 Polar Equations...... 110 10.1.11 Polynomial Functions...... 110 10.1.12 Power Functions...... 110 10.1.13 Quadratic Functions...... 110 10.1.14 Radical Functions...... 110 10.1.15 Rational Functions...... 110 10.1.16 Real Numbers...... 110 10.1.17 Sequences...... 110 10.1.18 Series...... 110 10.1.19 Sets...... 111 10.1.20 Systems of Equations...... 111 10.1.21 Transformations...... 111 10.1.22 Trigonometric Functions...... 111 10.1.23 Vectors...... 111 10.2 Calculus...... 111 10.2.1 Derivatives...... 111 10.2.2 Integrals...... 111 10.2.3 Limits...... 112 10.2.4 Polynomial Approximations And Series...... 112 v1.23 - 02/17/08 SAGE For Newbies 6/150

10.3 ...... 112 10.3.1 Data Analysis...... 112 10.3.2 Inferential Statistics...... 112 10.3.3 Normal Distributions...... 112 10.3.4 One Variable Analysis...... 112 10.3.5 Probability And Simulation...... 112 10.3.6 Two Variable Analysis...... 112

11 High School Science Problems...... 114 11.1 Physics...... 114 11.1.1 Atomic Physics...... 114 11.1.2 Circular Motion...... 114 11.1.3 Dynamics...... 114 11.1.4 Electricity And Magnetism...... 114 11.1.5 Fluids...... 114 11.1.6 Kinematics...... 114 11.1.7 Light...... 115 11.1.8 Optics...... 115 11.1.9 Relativity...... 115 11.1.10 Rotational Motion...... 115 11.1.11 Sound...... 115 11.1.12 Waves...... 115 11.1.13 Thermodynamics...... 115 11.1.14 Work...... 115 11.1.15 Energy...... 115 11.1.16 Momentum...... 116 11.1.17 Boiling...... 116 11.1.18 Buoyancy...... 116 11.1.19 Convection...... 116 11.1.20 Density...... 116 11.1.21 Diffusion...... 116 11.1.22 Freezing...... 116 11.1.23 Friction...... 116 11.1.24 Heat Transfer...... 117 11.1.25 Insulation...... 117 11.1.26 Newton's Laws...... 117 11.1.27 Pressure...... 117 11.1.28 Pulleys...... 117

12 Fundamentals Of Computation...... 118 12.1 What Is A Computer?...... 118 12.2 What Is A Symbol?...... 118 12.3 Computers Use Bit Patterns As Symbols...... 119 12.4 Contextual Meaning...... 122 12.5 Variables...... 122 12.6 Models...... 124 v1.23 - 02/17/08 SAGE For Newbies 7/150

12.7 Machine Language...... 125 12.8 Compilers And Interpreters...... 128 12.9 Algorithms...... 129 12.10 Computation...... 131 12.11 Diagrams Can Be Used To Record Algorithms...... 133 12.12 Calculating The Sum Of The Numbers Between 1 And 10...... 133 12.13 The Mathematics Part Of Mathematics Computing Systems...... 135

13 Setting Up A SAGE Server...... 136 13.1 An Introduction To Internet-based Technologies...... 136 13.1.1 How do multiple computers communicate with each other?...... 136 13.1.2 The TCP/IP protocol suite...... 137 13.1.3 Clients and servers...... 139 13.1.4 DHCP...... 139 13.1.5 DNS...... 140 13.1.6 Processes and ports...... 141 13.1.7 Well known ports, registered ports, and dynamic ports...... 145 13.1.7.1 Well known ports (0 - 1023)...... 145 13.1.7.2 Registered ports (1024 - 49151)...... 147 13.1.7.3 Dynamic/private ports (49152 - 65535)...... 147 13.1.8 The SSH (Secure SHell) service ...... 147 13.1.9 Using scp to copy files between machines on the network...... 148 13.2 SAGE's Architecture (in development)...... 148 13.3 -Based SAGE Distributions...... 150 13.4 The VMware Virtual Machine Distribution Of SAGE (Mostly For Windows Users)...... 150 v1.23 - 02/17/08 SAGE For Newbies 8/150

1 1 Preface

2 1.1 Dedication 3 This book is dedicated to Steve Yegge and his blog entry "Math Every 4 Day" ( http://steve.yegge.googlepages.com/math-every-day).

5 1.1 Acknowledgments 6 The following people have provided feedback on this book (if I forgot to include 7 your name on this list, please email me at ted.kosan at gmail.com): 8 Dave Dobbs 9 David Joyner 10 Greg Landweber 11 Jeremy Pedersen 12 William Stein 13 Steve Vonn 14 Joe Wetherell

15 1.2 Support Group 16 The support group for this book is called sage-support and it can be accessed 17 at: 18 http://groups.google.com/group/sage-support . Please place "[Newbies book]" in 19 the title of your email when you post to this group. v1.23 - 02/17/08 SAGE For Newbies 9/150

20 2 Introduction 21 SAGE is an open source mathematics computing environment (MCE) for 22 performing symbolic, algebraic, and numerical computations. Mathematics 23 computing environments are complex and it takes a significant amount of time 24 and effort to become proficient at using one. The amount of power that a 25 mathematics computing environment makes available to a user, however, is well 26 worth the effort needed to learn one. It will take a beginner a while to become 27 an expert at using SAGE, but fortunately one does not need to be a SAGE expert 28 in order to begin using it to solve problems.

29 2.1 What Is A Mathematics Computing Environment? 30 A mathematics computing environment is a set of computer programs that are 31 able to automatically perform a wide range of mathematics calculation 32 algorithms. Calculation algorithms exist for almost all areas of mathematics and 33 new algorithms are being developed all the time.

34 A significant number of mathematics computing environments have been created 35 since the 1960s and the following list contains some of the more popular ones:

36 http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems

37 Some environments are highly specialized and some are general purpose. Some 38 allow mathematics to be displayed and entered in traditional form (which is what 39 is found in most math textbooks), some are able to display traditional form 40 mathematics but need to have it input as text, and some are only able to have 41 mathematics displayed and entered as text.

42 As an example of the difference between traditional mathematics form and text 43 form, here is a formula which is displayed in traditional form:

44 and here is the same formula in text form:

45 A == x^2 + 4*h*x

46 Most mathematics computing environments contain some kind of mathematics- 47 oriented high-level programming language. This allows programs to be 48 developed which have access to the mathematics algorithms which are included 49 in the environment. Some of these mathematics-oriented programming 50 languages were created specifically for the environment they work in while 51 others are built around an existing programming language. v1.23 - 02/17/08 SAGE For Newbies 10/150

52 Some mathematics computing environments are proprietary and need to be 53 purchased while others are open source and available for free. Both kinds of 54 environments possess similar core capabilities, but they usually differ in other 55 areas.

56 Proprietary environments tend to be more polished than open source 57 environments and they often have graphical user interfaces that make inputting 58 and manipulating mathematics in traditional form relatively easy. However, 59 proprietary environments also have drawbacks. One drawback is that there is 60 always a chance that the company that owns it may go out of business and this 61 may make the environment unavailable for further use. Another drawback is 62 that users are unable to enhance a proprietary environment because the 63 environment's source code is not made available to users.

64 Open source mathematics computing environments usually do not have graphical 65 user interfaces, but their user interfaces are adequate for most purposes and the 66 environment's source code will always be available to whomever wants it. This 67 means that people can use the environment for as long as there is interest in it 68 and they can also enhance it as desired.

69 2.2 What Is SAGE? 70 SAGE is an open source mathematics computing environment that inputs 71 mathematics in textual form and displays it in either textual form or traditional 72 form. While most mathematics computing environments are self-contained 73 entities, SAGE takes the umbrella-like approach of providing some algorithms 74 itself and some by wrapping around other mathematics computing environments. 75 This strategy allows SAGE to provide the power of multiple mathematics 76 computing environments within an architecture that is easily able to evolve to 77 meet future needs.

78 SAGE is written in the powerful and very popular Python programming language 79 and the mathematics-oriented programming language that SAGE makes 80 available to users is an extension of Python. This means that expert SAGE users 81 must also be expert Python . Some knowledge of the Python 82 programming language is so critical to being able to successfully use SAGE that 83 a user's knowledge of Python can be used to help determine their level of SAGE 84 expertise. (see Table 1) v1.23 - 02/17/08 SAGE For Newbies 11/150

Level Knowledge SAGE Expert Knows Python well and SAGE well. SAGE Novice Knows Python but has only used SAGE for a short while. SAGE Newbie Does not know Python but has been exposed to at least 1 programming language. Programming Does not know how a computer works and has never Newbie programmed before. Table 1: SAGE user experience levels

85 This book is for SAGE Newbies. It assumes the reader has been exposed to at 86 least 1 programming language, but has never programmed in Python (if your 87 understanding of how computer programming works needs refreshing, you may 88 want to read through the Fundamentals Of Computing section of this book.) This 89 book will teach you enough Python to begin solving problems with SAGE. It will 90 help you to become a SAGE Novice, but you will need to learn Python from books 91 that are dedicated to it before you can become a SAGE Expert.

92 If you are a programming newbie, this book will probably be too advanced for 93 you. I have written a series of free books called The Professor and Pat 94 Programming Series (http://professorandpat.org) and they are designed for 95 programming newbies. If you are a programming newbie and are interested in 96 learning how to use SAGE, you might be interested in working through the 97 Professor and Pat Programming books first and then come back to this book 98 when you are finished with them.

99 The SAGE website (.org) contains more information about SAGE along 100 with other SAGE resources. v1.23 - 02/17/08 SAGE For Newbies 12/150

101 2.3 Accessing SAGE As A Web Service 102 The ways in which SAGE can be used are as flexible as its architecture. Most 103 SAGE beginners, however, will first use SAGE as a web service which is accessed 104 using a web browser. Any copy of SAGE can be configured to provide this web 105 service. Drawing 2.1 shows 3 SAGE web service scenarios:

Browser

Browser Scenario 1: Sage web service Sage available on Internet Server the Internet.

Browser Browser

Browser Browser

Network Sage Switch Server Scenario 2: Sage web service available on a Browser Local Area Network. Browser

Personal Scenario 3: Browser Computer Sage web service available on the same computer that the browser is running on. Sage Server

Drawing 2.1: Three SAGE web service scenarios. v1.23 - 02/17/08 SAGE For Newbies 13/150

2.3.1 Accessing SAGE As A Web Service Using Scenario 1 106 SAGE currently works best with the Firefox web browser and if you do not yet 107 have Firefox installed on your computer, it can be obtained at 108 http://mozilla.com/firefox.

109 The SAGE development team provides a public SAGE web service at 110 (http://sagenb.com) and this service can also be accessed from the top of the 111 SAGE homepage. We will now walk through the steps that are needed to sign up 112 for an account on this public SAGE web service.

113 Open a Firefox browser window and enter the following into the URL bar:

114 http://sagenb.com

115 The service will then display a Welcome page (see Drawing 2.2)

Drawing 2.2: SAGE Welcome screen.

116 The SAGE web service is called a SAGE Notebook because it simulates the kind 117 of notebook that mathematicians traditionally use to perform mathematical 118 calculations. Before you can access the Notebook, you must first sign up for a 119 Notebook account. Select the Sign up for a new SAGE Notebook account 120 link and a registration page will be displayed. (see Drawing 2.3) v1.23 - 02/17/08 SAGE For Newbies 14/150

Drawing 2.3: Signup page.

121 Enter a username and password in the Username and Password text boxes and 122 then press the Register Now button. A page will then be displayed that 123 indicates that the registration information was received and that a confirmation 124 message was sent to the email address that you provided.

125 Open this email and select the link that it contains. This will complete the 126 registration process and then you may go back to the Notebook's Welcome page 127 and log in.

128 After successfully logging into your Notebook account, a worksheet 129 management page will be displayed. (see Drawing 2.4)

Drawing 2.4: Worksheet management page. v1.23 - 02/17/08 SAGE For Newbies 15/150

130 Physical mathematics notebooks contain worksheets and therefore SAGE's 131 virtual notebook contains worksheets too. The worksheet management page 132 allows worksheets to be created, deleted, published on the Internet, etc. Since 133 this is a newly created Notebook, it does not contain any worksheets yet.

134 Create a new worksheet now by selecting the New Worksheet link. A 135 worksheet can either use special mathematics fonts to display mathematics in 136 traditional form or it can use images of these fonts. If the computer you are 137 working on does not have mathematics fonts installed, the worksheet will display 138 a message which indicates that it will use its built-in image fonts as an 139 alternative. (see Drawing 2.5)

Drawing 2.5: jsMath No TeXfonts alert.

140 The image fonts are not as clear as normal mathematics fonts, but they are 141 adequate for most purposes. Later you can install mathematics fonts on your 142 computer if you would like, but for now just press the Hide this Message 143 button and a page which contains a blank worksheet will be shown. (see Drawing 144 2.6) v1.23 - 02/17/08 SAGE For Newbies 16/150

Worksheet cell

Drawing 2.6: Blank worksheet.

145 Worksheets contain 1 or more cells which are used to enter source code that will 146 be executed by SAGE. Cells have rectangles drawn around them as shown in 147 Figure 6 and they are able to grow larger as more text is entered into them. 148 When a worksheet is first created, an initial cell is placed at the top of its work 149 area and this is where you will normally begin entering text.

150 2.4 Entering Source Code Into A SAGE Cell 151 Lets begin exploring SAGE by using it as a simple calculator. Place your mouse 152 cursor inside of the cell that is at the top of your worksheet. Notice that the 153 cursor is automatically placed against the left side of a new cell. You must 154 always begin each line of SAGE source code at the left side of a cell with no 155 indenting (unless you are instructed to do otherwise).

156 Type the following text, but do not press the enter key:

157 2 + 3

158 your worksheet should now look like Drawing 2.7. v1.23 - 02/17/08 SAGE For Newbies 17/150

Drawing 2.7: Entering text into a cell.

159 At this point you have 2 choices. You can either press the enter key or 160 you can hold down the shift key and press the enter key . If 161 you simply press the enter key, the cell will expand and drop the cursor down to 162 the next line so you can continue entering source code.

163 If you press shift and enter, however, the Worksheet will take all the source 164 code that has been typed into the cell and send it to the SAGE server through the 165 network so the server can execute the code. When SAGE is given source code 166 to execute, it will first process it using software called the SAGE preprocessor. 167 The preprocessor converts SAGE source code into Python source code so that it 168 can be executed using the Python environment that SAGE is built upon.

169 The converted source code is then passed to the Python environment where it is 170 compiled into a special form of machine language called Python bytecode. The 171 bytecode is then executed by a program that emulates a hardware CPU and this 172 program is called the Python interpreter.

173 Sometimes the server is able to execute the code quickly and sometimes it will 174 take a while. While the code is being executed by the server, the Worksheet will 175 display a small green vertical bar beneath the cell towards the left side of the 176 window as shown in Drawing 2.8. v1.23 - 02/17/08 SAGE For Newbies 18/150

Green bar indicates that the Sage server is currently executing the code that was submitted from the above cell by pressing .

Drawing 2.8: Executing the text in a cell.

177 When the server is finished executing the source code, the green bar will 178 disappear. If a displayable result was generated, this result is sent back to the 179 Worksheet and the Worksheet then displays it in the area that is directly beneath 180 the cell that the request was submitted from.

181 Press shift and enter in your cell now and in a few moments you should see a 182 result that looks like Drawing 2.9.

Drawing 2.9: The results of execution are displayed.

183 If code was submitted for execution from the bottom cell in the Notebook, a v1.23 - 02/17/08 SAGE For Newbies 19/150

184 blank cell is automatically added beneath this cell when the server has finished 185 executing the code.

186 Now enter the source code that is shown in the second cell in Drawing 2.10 and 187 execute it.

Drawing 2.10: A more complex calculation v1.23 - 02/17/08 SAGE For Newbies 20/150

188 3 SAGE Programming Fundamentals

189 3.1 Objects, Values, And Expressions 190 The source code lines

191 2 + 3

192 and

193 5 + 6*21/18 - 2^3

194 are both called expressions and the following is a definition of what an 195 expression is:

196 An expression in a programming language is a combination of values, 197 variables, operators, and functions that are interpreted (evaluated) 198 according to the particular rules of precedence and of association 199 for a particular programming language, which computes and then 200 produces another value. The expression is said to evaluate to that 201 value. As in mathematics, the expression is (or can be said to have) 202 its evaluated value; the expression is a representation of that 203 value. (http://en.wikipedia.org/wiki/Expression_(programming))

204 In a computer, a value is a pattern of bits in one or more memory locations that 205 mean something when interpreted using a given context. In SAGE, patterns of 206 bits in memory that have meaning are called objects. SAGE itself is built with 207 objects and the data that SAGE programs process are also represented as 208 objects. Objects are explained in more depth in Chapter 4.

209 In the above expressions, 2, 3, 5, 6, 21, and 18 are objects that are interpreted 210 using a context called the sage.rings.integer.Integer context. Contexts that 211 can be associated with objects are called types and an object that is of type 212 sage.rings.integer.Integer is used to represent integers.

213 There is a command in SAGE called type() which will return the type of any 214 object that is passed to it. Lets have the type() command tell us what the type of 215 the objects 3 and 21 are by executing the following code: (Note: from this point 216 forward, the source code that is to be entered into a cell, and any results that 217 need to be displayed, will be given without using a graphic worksheet screen 218 capture.)

219 type(3) 220 | 221 v1.23 - 02/17/08 SAGE For Newbies 21/150

222 type(21) 223 | 224

225 The way that a person tells the type() command what object they want to see the 226 type information for is by placing the object within the parentheses which are to 227 the right of the the name 'type'.

228 3.2 Operators 229 In the above expressions, the characters +, −, *, /, ^ are called operators and 230 their purpose is to tell SAGE what operations to perform on the objects in an 231 expression. For example, in the expression 2 + 3, the addition operator + tells 232 SAGE to add the integer 2 to the integer 3 and return the result. Since both the 233 objects 2 and 3 are of type sage.rings.integer.Integer, the result that is obtained 234 by adding them together will also be an object of type sage.rings.integer.Integer.

235 The subtraction operator is −, the multiplication operator is *, / is the 236 division operator, % is the remainder operator, and ^ is the exponent 237 operator. SAGE has more operators in addition to these and more information 238 about them can be found in Python documentation.

239 The following examples show the −, *, /,%, and ^ operators being used:

240 5 - 2 241 | 242 3

243 3*4 244 | 245 12

246 30/3 247 | 248 10

249 8%5 250 | 251 3

252 2^3 253 | 254 8

255 The − character can also be used to indicate a negative number: v1.23 - 02/17/08 SAGE For Newbies 22/150

256 -3 257 | 258 -3

259 Subtracting a negative number results in a positive number:

260 - -3 261 | 262 3

263 3.3 Operator Precedence 264 When expressions contain more than 1 operator, SAGE uses a set of rules called 265 operator precedence to determine the order in which the operators are applied 266 to the objects in the expression. Operator precedence is also referred to as the 267 order of operations. Operators with higher precedence are evaluated before 268 operators with lower precedence. The following table shows a subset of SAGE's 269 operator precedence rules with higher precedence operators being placed higher 270 in the table:

271 ^ Exponents are evaluated right to left.

272 *,%,/ Then multiplication, remainder, and division operations are evaluated left 273 to right.

274 +, − Finally, addition and subtraction are evaluated left to right.

275 Lets manually apply these precedence rules to the multi-operator expression we 276 used earlier. Here is the expression in source code form:

277 5 + 6*21/18 - 2^3

278 And here it is in traditional form:

279 According to the precedence rules, this is the order in which SAGE evaluates the 280 operations in this expression:

281 5 + 6*21/18 - 2^3 282 5 + 6*21/18 - 8 283 5 + 126/18 - 8 284 5 + 7 - 8 285 12 - 8 286 4

287 Starting with the first expression, SAGE evaluates the ^ operator first which v1.23 - 02/17/08 SAGE For Newbies 23/150

288 results in the 8 in the expression below it. In the second expression, the * 289 operator is executed next, and so on. The last expression shows that the final 290 result after all of the operators have been evaluated is 4.

291 3.4 Changing The Order Of Operations In An Expression 292 The default order of operations for an expression can be changed by grouping 293 various parts of the expression within parentheses. Parentheses force the code 294 that is placed inside of them to be evaluated before any other operators are 295 evaluated. For example, the expression 2 + 4*5 evaluates to 22 using the 296 default precedence rules:

297 2 + 4*5 298 | 299 22

300 If parentheses are placed around 4 + 5, however, the addition is forced to be 301 evaluated before the multiplication and the result is 30:

302 (2 + 4)*5 303 | 304 30

305 Parentheses can also be nested and nested parentheses are evaluated from the 306 most deeply nested parentheses outward:

307 ((2 + 4)*3)*5 308 | 309 90

310 Since parentheses are evaluated before any other operators, they are placed at 311 the top of the precedence table:

312 () Parentheses are evaluated from the inside out.

313 ^ Then exponents are evaluated right to left.

314 *,%,/ Then multiplication, remainder, and division operations are evaluated left 315 to right.

316 +, − Finally, addition and subtraction are evaluated left to right.

317 3.5 Variables 318 A variable is a name that can be associated with a memory address so that 319 humans can refer to bit pattern symbols in memory using a name instead of a 320 number. One way to create variables in SAGE is through assignment and it v1.23 - 02/17/08 SAGE For Newbies 24/150

321 consists of placing the name of a variable you would like to create on the left side 322 of an equals sign '=' and an expression on the right side of the equals sign. 323 When the expression returns an object, the object is assigned to the variable.

324 In the following example, a variable called box is created and the number 7 is 325 assigned to it:

326 box = 7 327 |

328 Notice that unlike earlier examples, a displayable result is not returned to the 329 worksheet because the result was placed in the variable box. If you want to see 330 the contents of box, type its name into a blank cell and then evaluate the cell:

331 box 332 | 333 7

334 As can be seen in this example, variables that are created in a given cell in a 335 worksheet are also available to the other cells in a worksheet. Variables exist in 336 a worksheet as long as the worksheet is open, but when the worksheet is closed, 337 the variables are lost. When the worksheet is reopened, the variables will need 338 to be created again by evaluating the cells they are assigned in. Variables can be 339 saved before a worksheet is closed and then loaded when the worksheet is 340 opened again, but this is an advanced topic which will be covered later.

341 SAGE variables are also case sensitive. This means that SAGE takes into account 342 the case of each letter in a variable name when it is deciding if two or more 343 variable names are the same variable or not. For example, the variable name 344 Box and the variable name box are not the same variable because the first 345 variable name starts with an upper case 'B' and the second variable name starts 346 with a lower case 'b'.

347 Programs are able to have more than 1 variable and here is a more sophisticated 348 example which uses 3 variables:

349 a = 2 350 |

351 b = 3 352 |

353 a + b 354 | 355 5 v1.23 - 02/17/08 SAGE For Newbies 25/150

356 answer = a + b 357 |

358 answer 359 | 360 5

361 The part of an expression that is on the right side of an equals sign '=' is always 362 evaluated first and the result is then assigned to the variable that is on the left 363 side of the equals sign.

364 When a variable is passed to the type() command, the type of the object that the 365 variable is assigned to is returned:

366 a = 4 367 type(a) 368 | 369

370 Data types and the type command will be covered more fully later.

371 3.6 Statements 372 Statements are the part of a programming language that is used to encode 373 algorithm logic. Unlike expressions, statements do not return objects and they 374 are used because of the various effects they are able to produce. Statements can 375 contain both expressions and statements and programs are constructed by using 376 a sequence of statements.

377 3.6.1 The print Statement 378 If more than one expression in a cell generates a displayable result, the cell will 379 only display the result from the bottommost expression. For example, this 380 program creates 3 variables and then attempts to display the contents of these 381 variables:

382 a = 1 383 b = 2 384 c = 3 385 a 386 b 387 c 388 | 389 3

390 In SAGE, programs are executed one line at a time, starting at the topmost line 391 of code and working downwards from there. In this example, the line a = 1 is v1.23 - 02/17/08 SAGE For Newbies 26/150

392 executed first, then the line b = 2 is executed, and so on. Notice, however, that 393 even though we wanted to see what was in all 3 variables, only the content of the 394 last variable was displayed.

395 SAGE has a statement called print that allows the results of expressions to be 396 displayed regardless of where they are located in the cell. This example is 397 similar to the previous one except print statements are used to display the 398 contents of all 3 variables:

399 a = 1 400 b = 2 401 c = 3 402 print a 403 print b 404 print c 405 | 406 1 407 2 408 3

409 The print statement will also print multiple results on the same line if commas 410 are placed between the expressions that are passed to it:

411 a = 1 412 b = 2 413 c = 3*6 414 print a,b,c 415 | 416 1 2 18

417 When a comma is placed after a variable or object which is being passed to the 418 print statement, it tells the statement not to drop the cursor down to the next 419 line after it is finished printing. Therefore, the next time a print statement is 420 executed, it will place its output on the same line as the previous print 421 statement's output.

422 Another way to display multiple results from a cell is by using semicolons ';'. In 423 SAGE, semicolons can be placed after statements as optional terminators, but 424 most of the time one will only see them used to place multiple statements on the 425 same line. The following example shows semicolons being used to allow 426 variables a, b, and c to be initialized on one line:

427 a=1;b=2;c=3 428 print a,b,c 429 | 430 1 2 3 v1.23 - 02/17/08 SAGE For Newbies 27/150

431 The next example shows how semicolons can be also used to output multiple 432 results from a cell:

433 a = 1 434 b = 2 435 c = 3*6 436 a;b;c 437 | 438 1 439 2 440 18

441 3.7 Strings 442 A string is a type of object that is used to hold text-based information. The 443 typical expression that is used to create a string object consists of text which is 444 enclosed within either double quotes or single quotes. Strings can be 445 referenced by variables just like numbers can and strings can also be displayed 446 by the print statement. The following example assigns a string object to the 447 variable 'a', prints the string object that 'a' references, and then also displays its 448 type:

449 a = "Hello, I am a string." 450 print a 451 type(a) 452 | 453 Hello, I am a string. 454

455 3.8 Comments 456 Source code can often be difficult to understand and therefore all programming 457 languages provide the ability for comments to be included in the code. 458 Comments are used to explain what the code near them is doing and they are 459 usually meant to be read by a human looking at the source code. Comments are 460 ignored when the program is executed.

461 There are two ways that SAGE allows comments to be added to source code. The 462 first way is by placing a pound sign '#' to the left of any text that is meant to 463 serve as a comment. The text from the pound sign to the end of the line the 464 pound sign is on will be treated as a comment. Here is a program that contains 465 comments which use a pound sign:

466 #This is a comment. 467 x = 2 #Set the variable x equal to 2. 468 print x v1.23 - 02/17/08 SAGE For Newbies 28/150

469 | 470 2

471 When this program is executed, the text that starts with a pound sign is ignored.

472 The second way to add comments to a SAGE program is by enclosing the 473 comments in a set of triple quotes. This option is useful when a comment is too 474 large to fit on one line. This program shows a triple quoted comment:

475 """ 476 This is a longer comment and it uses 477 more than one line. The following 478 code assigns the number 3 to variable 479 x and then it prints x. 480 """

481 x = 3 482 print x 483 | 484 3

485 3.9 Conditional Operators 486 A conditional operator is an operator that is used to compare two objects. 487 Expressions that contain conditional operators return a boolean object and a 488 boolean object is one that can either be True or False. Table 2 shows the 489 conditional operators that SAGE uses:

Operator Description x == y Returns True if the two objects are equal and False if they are not equal. Notice that == performs a comparison and not an assignment like = does. x <> y Returns True if the objects are not equal and False if they are equal. x != y Returns True if the objects are not equal and False if they are equal. x < y Returns True if the left object is less than the right object and False if the left object is not less than the right object. x <= y Returns True if the left object is less than or equal to the right object and False if the left object is not less than or equal to the right object. x > y Returns True if the left object is greater than the right object and False if the left object is not greater than the right object. x >= y Returns True if the left object is greater than or equal to the right object and False if the left object is not greater than or equal to the right object. Table 2: Conditional Operators v1.23 - 02/17/08 SAGE For Newbies 29/150

490 The following examples show each of the conditional operators in Table 2 being 491 used to compare objects that have been placed into variables x and y:

492 # Example 1. 493 x = 2 494 y = 3

495 print x, "==", y, ":", x == y 496 print x, "<>", y, ":", x <> y 497 print x, "!=", y, ":", x != y 498 print x, "<", y, ":", x < y 499 print x, "<=", y, ":", x <= y 500 print x, ">", y, ":", x > y 501 print x, ">=", y, ":", x >= y 502 | 503 2 == 3 : False 504 2 <> 3 : True 505 2 != 3 : True 506 2 < 3 : True 507 2 <= 3 : True 508 2 > 3 : False 509 2 >= 3 : False

510 # Example 2. 511 x = 2 512 y = 2

513 print x, "==", y, ":", x == y 514 print x, "<>", y, ":", x <> y 515 print x, "!=", y, ":", x != y 516 print x, "<", y, ":", x < y 517 print x, "<=", y, ":", x <= y 518 print x, ">", y, ":", x > y 519 print x, ">=", y, ":", x >= y 520 | 521 2 == 2 : True 522 2 <> 2 : False 523 2 != 2 : False 524 2 < 2 : False 525 2 <= 2 : True 526 2 > 2 : False 527 2 >= 2 : True

528 # Example 3. 529 x = 3 530 y = 2 v1.23 - 02/17/08 SAGE For Newbies 30/150

531 print x, "==", y, ":", x == y 532 print x, "<>", y, ":", x <> y 533 print x, "!=", y, ":", x != y 534 print x, "<", y, ":", x < y 535 print x, "<=", y, ":", x <= y 536 print x, ">", y, ":", x > y 537 print x, ">=", y, ":", x >= y 538 | 539 3 == 2 : False 540 3 <> 2 : True 541 3 != 2 : True 542 3 < 2 : False 543 3 <= 2 : False 544 3 > 2 : True 545 3 >= 2 : True

546 Conditional operators are placed at a lower level of precedence than the other 547 operators we have covered to this point:

548 () Parentheses are evaluated from the inside out.

549 ^ Then exponents are evaluated right to left.

550 *,%,/ Then multiplication, remainder, and division operations are evaluated left 551 to right.

552 +, − Then addition and subtraction are evaluated left to right.

553 ==,<>,!=,<,<=,>,>= Finally, conditional operators are evaluated.

554 3.10 Making Decisions With The if Statement 555 All programming languages provide the ability to make decisions and the most 556 commonly used statement for making decisions in SAGE is the if statement.

557 A simplified syntax specification for the if statement is as follows:

558 if : 559 560 561 562 . 563 . 564 .

565 The way an if statement works is that it evaluates the expression to its v1.23 - 02/17/08 SAGE For Newbies 31/150

566 immediate right and then looks at the object that is returned. If this object is 567 "true", the statements that are inside the if statement are executed. If the 568 object is "false", the statements inside of the if are not executed.

569 In SAGE, an object is "true" if it is nonzero or nonempty and it is "false" if it is 570 zero or empty. An expression that contains one or more conditional operators 571 will return a boolean object which will be either True or False.

572 The way that statements are placed inside of a statement is by putting a colon ':' 573 at the end of the statement's header and then placing one or more statements 574 underneath it. The statements that are placed underneath an enclosing 575 statement must each be indented one or more tabs or spaces from the left side 576 of the enclosing statement. All indented statements, however, must be indented 577 the same way and the same amount. One or more statements that are indented 578 like this are referred to as a block of code.

579 The following program uses an if statement to determine if the number in 580 variable x is greater than 5. If x is greater than 5, the program will print 581 "Greater" and then "End of program".

582 x = 6

583 print x > 5

584 if x > 5: 585 print x 586 print "Greater"

587 print "End of program" 588 | 589 True 590 6 591 Greater 592 End of program

593 In this program, x has been set to 6 and therefore the expression x > 5 is true. 594 When this expression is printed, it prints the boolean object True because 6 is 595 greater than 5.

596 When the if statement evaluates the expression and determines it is True, it then 597 executes the print statements that are inside of it and the contents of variable x 598 are printed along with the string "Greater". If additional statements needed to 599 be placed within the if statement, they would have been added underneath the 600 print statements at the same level of indenting.

601 Finally, the last print statement prints the string "End of program" regardless of v1.23 - 02/17/08 SAGE For Newbies 32/150

602 what the if statement does.

603 Here is the same program except that x has been set to 4 instead of 6:

604 x = 4

605 print x > 5

606 if x > 5: 607 print x 608 print "Greater."

609 print "End of program." 610 | 611 False 612 End of program.

613 This time the expression x > 4 returns a False object which causes the if 614 statement to not execute the statements that are inside of it.

615 3.11 The and, or, And not Boolean Operators 616 Sometimes one wants to check if two or more expressions are all true and the 617 way to do this is with the and operator:

618 a = 7 619 b = 9 620 print a < 5 and b < 10 621 print a > 5 and b > 10 622 print a < 5 and b > 10 623 print a > 5 and b < 10 624 if a > 5 and b < 10: 625 print "These expressions are both true." 626 | 627 False 628 False 629 False 630 True 631 These expressions are both true.

632 At other times one wants to determine if at least one expression in a group is 633 true and this is done with the or operator:

634 a = 7 635 b = 9 636 print a < 5 or b < 10 v1.23 - 02/17/08 SAGE For Newbies 33/150

637 print a > 5 or b > 10 638 print a > 5 or b < 10 639 print a < 5 or b > 10

640 if a < 5 or b < 10: 641 print "At least one of these expressions is true." 642 | 643 True 644 True 645 True 646 False 647 At least one of these expressions is true.

648 Finally, the not operator can be used to change a True result to a False result, 649 and a False result to a True result:

650 a = 7 651 print a > 5 652 print not a > 5 653 | 654 True 655 False

656 Boolean operators are placed at a lower level of precedence than the other 657 operators we have covered to this point:

658 () Parentheses are evaluated from the inside out.

659 ^ Then exponents are evaluated right to left.

660 *,%,/ Then multiplication, remainder, and division operations are evaluated left 661 to right.

662 +, − Then addition and subtraction are evaluated left to right.

663 ==,<>,!=,<,<=,>,>= Then conditional operators are evaluated.

664 not The boolean operators are evaluated last.

665 and

666 or v1.23 - 02/17/08 SAGE For Newbies 34/150

667 3.12 Looping With The while Statement 668 Many kinds of machines, including computers, derive much of their power from 669 the principle of repeated cycling. SAGE provides a number of ways to implement 670 repeated cycling in a program and these ways range from straight-forward to 671 subtle. We will begin discussing looping in SAGE by starting with the straight- 672 forward while statement.

673 The syntax specification for the while statement is as follows:

674 while : 675 676 677 678 . 679 . 680 .

681 The while statement is similar to the if statement except it will repeatedly 682 execute the statements it contains as long as the expression to the right of its 683 header is true. As soon as the expression returns a False object, the while 684 statement skips the statements it contains and execution continues with the 685 statement that immediately follows the while statement (if there is one).

686 The following example program uses a while loop to print the integers from 1 to 687 10:

688 # Print the integers from 1 to 10.

689 x = 1 #Initialize a counting variable to 1 outside of the loop.

690 while x <= 10: 691 print x 692 x = x + 1 #Increment x by 1. 693 | 694 1 695 2 696 3 697 4 698 5 699 6 700 7 701 8 702 9 703 10

704 In this program, a single variable called x is created. It is used to tell the print v1.23 - 02/17/08 SAGE For Newbies 35/150

705 statement which integer to print and it is also used in the expression that 706 determines if the while loop should continue to loop or not.

707 When the program is executed, 1 is placed into x and then the while statement is 708 entered. The expression x <= 10 becomes 1 <= 10 and, since 1 is less than or 709 equal to 10, a boolean object containing True is returned by the expression.

710 The while statement sees that the expression returned a true object and 711 therefore it executes all of the statements inside of itself from top to bottom.

712 The print statement prints the current contents of x (which is 1) then x = x + 1 is 713 executed.

714 The expression x = x + 1 is a standard expression form that is used in many 715 programming languages. Each time an expression in this form is evaluated, it 716 increases the variable it contains by 1. Another way to describe the effect this 717 expression has on x is to say that it increments x by 1.

718 In this case x contains 1 and, after the expression is evaluated, x contains 2.

719 After the last statement inside of a while statement is executed, the while 720 statement reevaluates the expression to the right of its header to determine 721 whether it should continue looping or not. Since x is 2 at this point, the 722 expression returns True and the code inside the while statement is executed 723 again. This loop will be repeated until x is incremented to 11 and the expression 724 returns False.

725 The previous program can be adjusted in a number of ways to achieve different 726 results. For example, the following program prints the integers from 1 to 100 by 727 increasing the 10 in the expression which is at the right side of the while header 728 to 100. A comma has been placed after the print statement so that its output is 729 displayed on the same line until it encounters the right side of the window.

730 # Print the integers from 1 to 100.

731 x = 1

732 while x <= 100: 733 print x, 734 x = x + 1 #Increment x by 1. 735 | 736 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 737 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 738 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 739 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 740 100 v1.23 - 02/17/08 SAGE For Newbies 36/150

741 The following program prints the odd integers from 1 to 99 by changing the 742 increment value in the increment expression from 1 to 2:

743 # Print the odd integers from 1 to 99.

744 x = 1

745 while x <= 100: 746 print x, 747 x = x + 2 #Increment x by 2. 748 | 749 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 750 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

751 Finally, this program prints the numbers from 1 to 100 in reverse order:

752 # Print the integers from 1 to 100 in reverse order.

753 x = 100

754 while x >= 1: 755 print x, 756 x = x - 1 #Decrement x by 1. 757 | 758 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 759 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 760 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 761 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 762 1

763 In order to achieve this result, this program had to initialize x to 100, check to 764 see if x was greater than or equal to 1 (x >= 1) to continue looping, and 765 decrement x by subtracting 1 from it instead of adding 1 to it.

766 3.13 Long-Running Loops, Infinite Loops, And 767 Interrupting Execution 768 It is easy to create a loop that will execute a large number of times, or even an 769 infinite number of times, either on purpose or by mistake. When you execute a 770 program that contains an infinite loop, it will run until you tell SAGE to 771 interrupt its execution. This is done by selecting the Action menu which is 772 near the upper left part of the worksheet and then selecting the Interrupt menu 773 item. Programs with long-running loops can be interrupted this way too. In both 774 cases, the vertical green execution bar will indicate that the program is currently 775 executing and the green bar will disappear after the program has been 776 interrupted. v1.23 - 02/17/08 SAGE For Newbies 37/150

777 This program contains an infinite loop:

778 #Infinite loop example program.

779 x = 1 780 while x < 10: 781 answer = x + 1 782 |

783 Since the contents of x is never changed inside the loop, the expression x < 10 784 always evaluates to True which causes the loop to continue looping.

785 Execute this program now and then interrupt it using the worksheet's Interrupt 786 command. Sometimes simply interrupting the worksheet is not enough to stop 787 execution and then you will need to select Action -> Restart worksheet. When 788 a worksheet is restarted, however, all variables are set back to their initial 789 conditions so the cells that assigned values to these variables will each need to 790 be executed again.

791 3.14 Inserting And Deleting Worksheet Cells 792 If you need to insert a new worksheet cell between two existing worksheet cells, 793 move your mouse cursor between the two cells just above the bottom one and a 794 horizontal blue bar will appear. Click on this blue bar and a new cell will be 795 inserted into the worksheet at that point.

796 If you want to delete a cell, delete all of the text in the cell so that it is empty. 797 Make sure the cursor is in the now empty cell and then press the backspace key 798 on your keyboard. The cell will then be deleted.

799 3.15 Introduction To More Advanced Object Types 800 Up to this point, we have only used objects of type 'sage.rings.integer.Integer' 801 and of type 'str'. However, SAGE includes a large number of mathematical and 802 nonmathematical object types that can be used for a wide variety of purposes. 803 The following sections introduce two additional mathematical object types and 804 two nonmathematical object types.

3.15.1 Rational Numbers 805 Rational numbers are held in objects of type sage.rings.rational.Rational. The 806 following example prints the type of the rational number 1/2, assigns 1/2 to 807 variable x, prints x, and then displays the type of the object that x references: 808 print type(1/2) 809 x = 1/2 810 print x 811 type(x) v1.23 - 02/17/08 SAGE For Newbies 38/150

812 | 813 814 1/2 815

816 The following code was entered into a separate cell in the worksheet after the 817 previous code was executed. It shows two rational numbers being added 818 together and the result, which is also a rational number, being assigned to the 819 variable y: 820 y = x + 3/4 821 print y 822 type(y) 823 | 824 5/4 825

826 If a rational number is added to an integer number, the result is placed into an 827 object of type sage.rings.rational.Rational:

828 x = 1 + 1/2 829 print x 830 type(x) 831 | 832 3/2 833

3.15.2 Real Numbers 834 Real numbers are held in objects of type sage.rings.real_mpfr.RealNumber. 835 The following example prints the type of the real number .5, assigns .5 to 836 variable x, prints x, and then displays the type of the object that x references: 837 print type(.5) 838 x = .5 839 print x 840 type(x) 841 | 842 843 0.500000000000000 844

845 The following code was entered in a separate cell in the worksheet after the 846 previous code was executed. It shows two real numbers being added together 847 and the result, which is also a real number, being assigned to the variable y: 848 y = x + .75 v1.23 - 02/17/08 SAGE For Newbies 39/150

849 print y 850 type(y) 851 | 852 1.25000000000000 853

854 If a real number is added to a rational number, the result is placed into an object 855 of type sage.rings.real_mpfr.RealNumber:

856 x = 1/2 + .75 857 print x 858 type(x) 859 | 860 1.25000000000000 861

3.15.3 Objects That Hold Sequences Of Other Objects: Lists And Tuples 862 The list object type is designed to hold other objects in an ordered collection or 863 sequence. Lists are very flexible and they are one of the most heavily used 864 object types in SAGE. Lists can hold objects of any type, they can grow and 865 shrink as needed, and they can be nested. Objects in a list can be accessed by 866 their position in the list and they can also be replaced by other objects. A list's 867 ability to grow, shrink, and have its contents changed makes it a mutable object 868 type. 869 One way to create a list is by placing 0 or more objects or expressions inside of a 870 pair of square braces. The following program begins by printing the type of a 871 list. It then creates a list that contains the numbers 50, 51, 52, and 53, assigns it 872 to the variable x, and prints x. 873 Next, it prints the objects that are in positions 0 and 3, replaces the 53 at 874 position 3 with 100, prints x again, and finally prints the type of the object that x 875 refers to:

876 print type([]) 877 x = [50,51,52,53] 878 print x 879 print x[0] 880 print x[3] 881 x[3] = 100 882 print x 883 type(x) 884 | 885 v1.23 - 02/17/08 SAGE For Newbies 40/150

886 [50, 51, 52, 53] 887 50 888 53 889 [50, 51, 52, 100] 890

891 Notice that the first object in a list is placed at position 0 instead of position 1 892 and that this makes the position of the last object in the list 1 less than the 893 length of the list. Also notice that an object in a list is accessed by placing a pair 894 of square brackets, which contain its position number, to the right of a variable 895 that references the list. 896 The next example shows that different types of objects can be placed into a list:

897 x = [1, 1/2, .75, 'Hello', [50,51,52,53]] 898 print x 899 | 900 [1, 1/2, 0.750000000000000, 'Hello', [50, 51, 52, 53]]

901 Tuples are also sequences and are similar to lists except they are immutable. 902 They are created using a pair of parentheses instead of a pair of square 903 brackets and being immutable means that once a tuple object has been created, 904 it cannot grow, shrink, or change the objects it contains. 905 The following program is similar to the first example list program, except it uses 906 a tuple instead of a list, it does not try to change the object in position 4, and it 907 uses the semicolon technique to display multiple results instead of print 908 statements:

909 print type(()) 910 x = (50,51,52,53) 911 x;x[0];x[3];x;type(x) 912 | 913 914 (50, 51, 52, 53) 915 50 916 53 917 (50, 51, 52, 53) 918

3.15.3.1 Tuple Packing And Unpacking 919 When multiple values separated by commas are assigned to a single variable, the 920 values are automatically placed into a tuple and this is called tuple packing:

921 t = 1,2 v1.23 - 02/17/08 SAGE For Newbies 41/150

922 t 923 | 924 (1, 2)

925 When a tuple is assigned to multiple variables which are separated by commas, 926 this is called tuple unpacking:

927 a,b,c = (1,2,3) 928 a;b;c 929 | 930 1 931 2 932 3

933 A requirement with tuple unpacking is that the number of objects in the tuple 934 must match the number of variables on the left side of the equals sign.

935 3.16 Using while Loops With Lists And Tuples 936 Statements that loop can be used to select each object in a list or a tuple in turn 937 so that an operation can be performed on these objects. The following program 938 uses a while loop to print each of the objects in a list:

939 #Print each object in the list. 940 x = [50,51,52,53,54,55,56,57,58,59] 941 y = 0 942 while y <= 9: 943 print x[y] 944 y = y + 1 945 | 946 50 947 51 948 52 949 53 950 54 951 55 952 56 953 57 954 58 955 59

956 A loop can also be used to search through a list. The following program uses a 957 while loop and an if statement to search through a list to see if it contains the 958 number 53. If 53 is found in the list, a message is printed. v1.23 - 02/17/08 SAGE For Newbies 42/150

959 #Determine if 53 is in the list. 960 x = [50,51,52,53,54,55,56,57,58,59] 961 y = 0 962 while y <= 9: 963 if x[y] == 53: 964 print "53 was found in the list at position", y 965 y = y + 1 966 | 967 53 was found in the list at position 3

968 3.17 The in Operator 969 Looping is such a useful capability that SAGE even has an operator called in that 970 loops internally. The in operator is able to automatically search a list to 971 determine if it contains a given object. If it finds the object, it will return True 972 and if it doesn't find the object, it will return False. The following programs 973 shows both cases:

974 print 53 in [50,51,52,53,54,55,56,57,58,59] 975 print 75 in [50,51,52,53,54,55,56,57,58,59] 976 | 977 True 978 False

979 The not operator can also be used with the in operator to change its result:

980 print 53 not in [50,51,52,53,54,55,56,57,58,59] 981 print 75 not in [50,51,52,53,54,55,56,57,58,59] 982 | 983 False 984 True

985 3.18 Looping With The for Statement 986 The for statement uses a loop to index through a list or tuple like the while 987 statement does, but it is more flexible and automatic. Here is a simplified syntax 988 specification for the for statement:

989 for in : 990 991 992 993 . 994 . 995 . v1.23 - 02/17/08 SAGE For Newbies 43/150

996 In this syntax, is usually a variable and is usually an object 997 that contains other objects. In the remainder of this section, lets assume that 998 is a list. The for statement will select each object in the list in turn, 999 assign it to , and then execute the statements that are inside its 1000 indented code block. The following program shows a for statement being used 1001 to print all of the items in a list:

1002 for x in [50,51,52,53,54,55,56,57,58,59]: 1003 print x 1004 | 1005 50 1006 51 1007 52 1008 53 1009 54 1010 55 1011 56 1012 57 1013 58 1014 59

1015 3.19 Functions 1016 Programming functions are statements that consist of named blocks of code 1017 that can be executed one or more times by being called from other parts of the 1018 program. Functions can have objects passed to them from the calling code and 1019 they can also return objects back to the calling code. An example of a function is 1020 the type() command which we have been using to determine the types of objects.

1021 Functions are one way that SAGE enables code to be reused. Most programming 1022 languages allow code to be reused in this way, although in other languages these 1023 type of code reuse statements are sometimes called subroutines or 1024 procedures.

1025 Function names use all lower case letters. If a function name contains more than 1026 one word (like calculatesum) an underscore can be placed between the words to 1027 improve readability (calculate_sum).

1028 3.20 Functions Are Defined Using the def Statement 1029 The statement that is used to define a function is called def and its syntax 1030 specification is as follows:

1031 def (arg1, arg2, ... argN): 1032 1033 v1.23 - 02/17/08 SAGE For Newbies 44/150

1034 1035 . 1036 . 1037 .

1038 The def statement contains a header which includes the function's name along 1039 with the arguments that can be passed to it. A function can have 0 or more 1040 arguments and these arguments are placed within parentheses. The statements 1041 that are to be executed when the function is called are placed inside the function 1042 using an indented block of code.

1043 The following program defines a function called addnums which takes two 1044 numbers as arguments, adds them together, and returns their sum back to the 1045 calling code using a return statement:

1046 def addnums(num1, num2): 1047 """ 1048 Returns the sum of num1 and num2. 1049 """ 1050 answer = num1 + num2 1051 return answer

1052 #Call the function and have it add 2 to 3. 1053 a = addnums(2, 3) 1054 print a

1055 #Call the function and have it add 4 to 5. 1056 b = addnums(4, 5) 1057 print b 1058 | 1059 5 1060 9

1061 The first time this function is called, it is passed the numbers 2 and 3 and these 1062 numbers are assigned to the variables num1 and num2 respectively. Argument 1063 variables that have objects passed to them during a function call can be used 1064 within the function as needed.

1065 Notice that when the function returns back to the caller, the object that was 1066 placed to the right of the return statement is made available to the calling code. 1067 It is almost as if the function itself is replaced with the object it returns. Another 1068 way to think about a returned object is that it is sent out of the left side of the 1069 function name in the calling code, through the equals sign, and is assigned to the 1070 variable. In the first function call, the object that the function returns is being 1071 assigned to the variable 'a' and then this object is printed. v1.23 - 02/17/08 SAGE For Newbies 45/150

1072 The second function call is similar to the first call, except it passes different 1073 numbers (4, 5) to the function.

1074 3.21 A Subset Of Functions Included In SAGE 1075 SAGE includes a large number of pre-written functions that can be used for a 1076 wide variety of purposes. Table 3 contains a subset of these functions and a 1077 longer list of functions can be found in SAGE's documentation. A more complete 1078 list of functions can be found in the SAGE Reference Manual. v1.23 - 02/17/08 SAGE For Newbies 46/150

Function Name Description abs Return the absolute value of the argument. acos The arccosine function. add Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. additive_order Return the additive order of x. asin The arcsine function. atan The arctangent function. binomial Return the binomial coefficient. ceil The ceiling function. combinations A combination of a multiset (a list of objects which may contain the same object several times) mset is an unordered selection without repetitions and is represented by a sorted sublist of mset. Returns the set of all combinations of the multiset mset with k elements. complex Create a complex number from a real part and an optional imaginary part. This is equivalent to (real + imag*1j) where imag defaults to 0. cos The cosine function. cosh The hyperbolic cosine function. coth The hyperbolic cotangent function. csch The hyperbolic cosecant function. denominator Return the denominator of x. derivative The derivative of f. det Return the determinant of x. diff The derivative of f. dir Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. divisors Returns a list of all positive integer divisors. dumps Dump obj to a string s. To recover obj, use loads(s). e The base of the natural logarithm. eratosthenes Return a list of the primes <= n. exists If S contains an element x such that P(x) is True, this function returns True and the element x. Otherwise it returns False and None. exp The exponential function, exp(x) = e^x. expand Returns the expanded form of a polynomial. factor Returns the factorization of the integer n as a sorted list of tuples (p,e). factorial Compute the factorial of n, which is the product of 1 * 2 * 3 ... (n-1) n. v1.23 - 02/17/08 SAGE For Newbies 47/150

fibonacci Returns then n-th Fibonacci number. fibonacci_sequence Returns an iterator over the Fibonacci sequence, for all fibonacci numbers f_n from n = start up to (but not including) n = stop. fibonacci_xrange Returns an iterator over all of the Fibonacci numbers in the given range, including f_n = start up to, but not including, f_n = stop. find_root Numerically find a root of f on the closed interval [a,b (or [b,a]) if possible, where f is a function in the one variable.

floor The floor function. forall If P(x) is true every x in S, return True and None. If there is some element x in S such that P is not True, return False and x. forget Forget the given assumption, or call with no arguments to forget all assumptions. Here an assumption is some sort of symbolic constraint. function Create a formal symbolic function with the name *s*. gaussian_binomial Return the gaussian binomial. gcd The greatest common divisor of a and b. generic_power The m-th power of a, where m is a non-negative. get_memory_usage Return memory usage. hex Return the hexadecimal representation of an integer or long integer. imag Return the imaginary part of x. imaginary Return the imaginary part of a complex number. integer_ceil Return the ceiling of x. integer_floor Return the largest integer <= x. integral Return an indefinite integral of an object x. integrate The integral of f. interval Integers between a and b inclusive (a and b integers). is_AlgebraElement Return True if x is of type AlgebraElement. is_commutative is_ComplexNumber is_even Return whether or not an integer x is even, e.g., divisible by 2. is_Functor is_Infinite is_Integer is_odd Return whether or not x is odd. This is by definition the complement of is_even. is_power_of_two This function returns True if and only if n is a power of 2 is_prime Returns True if x is prime, and False otherwise. is_prime_power Returns True if x is a prime power, and False otherwise. v1.23 - 02/17/08 SAGE For Newbies 48/150

is_pseudoprime Returns True if x is a pseudo-prime, and False otherwise. is_RealNumber Return True if x is of type RealNumber, meaning that it is an element of the MPFR real field with some precision. is_Set Returns true if x is a SAGE Set. is_square Returns whether or not n is square, and if n is a square also returns the square root. If n is not square, also returns None. is_SymbolicExpression isqrt Return an integer square root, i.e., the floor of a square root. laplace Attempts to compute and return the Laplace transform of self. latex Use latex(...) to typeset a SAGE object. lcm The least common multiple of a and b, or if a is a list and b is omitted the least common multiple of all elements of v. len Returns the number of items of a sequence or mapping. lim Return the limit as the variable v approaches a from the given direction. limit Return the limit as the variable v approaches a from the given direction. list list() -> new list, list(sequence) -> new list initialized from sequence's items list_plot list_plot takes a single list of data, in which case it forms a list of tuples (i,di) where i goes from 0 to len(data)-1 and di is the ith data value, and puts points at those tuple values. list_plot also takes a list of tuples (dxi, dyi) where dxi is the ith data representing the x- value, and dyi is the ith y-value if plotjoined=True, then a line spanning all the data is drawn instead. load Load SAGE object from the file with name filename, which will have an .sobj extension added if it doesn't have one. NOTE: There is also a special SAGE command (that is not available in Python) called load that you use by typing sage: load filename.sage loads Recover an object x that has been dumped to a string s using s = dumps(x). log The natural logarithm of the real number 2. matrix Create a matrix. max With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. min With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument. minimal_polynomial Return the minimal polynomial of x. mod mrange Return the multirange list with given sizes and type. mul Return the product of the elements in the list x. next_prime The next prime greater than the integer n. next_prime_power The next prime power greater than the integer n. If n is a prime v1.23 - 02/17/08 SAGE For Newbies 49/150

norm Return the norm of x. normalvariate Normal distribution. nth_prime number_of_arrangements Returns the size of arrangements(mset,k). number_of_combinations Returns the size of combinations(mset,k). number_of_derangements Returns the size of derangements(mset). number_of_divisors Return the number of divisors of the integer n. number_of_permutations Returns the size of permutations(mset). numerator Return the numerator of x. numerical_integral Returns the numerical integral of the function on the interval from xmin to xmax and an error bound. numerical_sqrt Return a square root of x. oct Return the octal representation of an integer or long integer. order Return the order of x. If x is a ring or module element, this is the additive order of x. parametric_plot parametric_plot takes two functions as a list or a tuple and make a plot with the first function giving the x coordinates and the second function giving the y coordinates. parent Return x.parent() if defined, or type(x) if not. permutations A permutation is represented by a list that contains exactly the same elements as mset, but possibly in different order. pg Permutation groups. In SAGE a permutation is represented as either a string that defines a permutation using disjoint cycle notation, or a list of tuples, which represent disjoint cycles. pi The ratio of a circle's circumference to its diameter. plot pow With two arguments, equivalent to x^y. With three arguments, equivalent to (x^y) % z, but may be more efficient (e.g. for longs) power_mod The m-th power of a modulo the integer n. prange List of all primes between start and stop-1, inclusive. previous_prime The largest prime < n. previous_prime_power The largest prime power < n. prime_divisors The prime divisors of the integer n, sorted in increasing order. prime_factors The prime divisors of the integer n, sorted in increasing order. prime_powers List of all positive primes powers between start and stop-1, inclusive. primes Returns an iterator over all primes between start and stop-1, inclusive. primes_first_n Return the first n primes. prod Return the product of the elements in the list x. quo Return the quotient object x/y, e.g., a quotient of numbers or of a v1.23 - 02/17/08 SAGE For Newbies 50/150

polynomial ring x by the ideal generated by y, etc. quotient Return the quotient object x/y, e.g., a quotient of numbers or of a polynomial ring x by the ideal generated by y, etc. random Returns a random number in the interval [0, 1]. random_prime Returns a random prime p between 2 and n (i.e. 2 <= p <= n). randrange Choose a random item from range(start, stop[, step]). range Returns a list containing an arithmetic progression of integers. rational_reconstruction This function tries to compute x/y, where x/y is rational number. real Return the real part of x. reduce Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. repr Return the canonical string representation of the object. reset Delete all user defined variables, reset all globals variables back to their default state, and reset all interfaces to other computer algebra systems. If vars is specified, just restore the value of vars and leave all other variables alone (i.e., call restore). restore Restore predefined global variables to their default values. round Round a number to a given precision in decimal digits (default 0 digits). This always returns a real double field element. sample Chooses k unique random elements from a population sequence. save Save obj to the file with name filename, which will have an .sobj extension added if it doesn't have one. This will *replace* the contents of filename. save_session Save all variables that can be saved wto the given filename. search Return (True,i) where i is such that v[i] == x if there is such an i, or (False,j) otherwise, where j is the position that a should be inserted so that v remains sorted. search_doc Full text search of the SAGE HTML documentation for lines containing s. search_src Search sage source code for lines containing s. sec The secant function. sech The hyperbolic secant function. seed seq A mutable list of elements with a common guaranteed universe, which can be set immutable. set Build an unordered collection of unique elements. show Show a graphics object x. show_default Set the default for showing plots using the following commands: plot, parametric_plot, polar_plot, and list_plot. shuffle sigma Return the sum of the k-th powers of the divisors of n. v1.23 - 02/17/08 SAGE For Newbies 51/150

simplify Simplify the expression f. sin The sine function. sinh The hyperbolic sine function. sleep slice Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). slide Use latex(...) to typeset a SAGE object. Use %slide instead to typeset slides. solve Algebraically solve an equation or system of equations for given variables. sorted sqrt The square root function. This is a symbolic square root. square_free_part Return the square free part of x, i.e., a divisor z such that x = z y^2, for a perfect square y^2. srange Return list of numbers \code{a, a+step, ..., a+k*step}, where a +k*step < b and a+(k+1)*step > b. The type of the entries in the list are the type of the starting value. str Return a nice string representation of the object. subfactorial Subfactorial or rencontres numbers, or derangements: number of permutations of $n$ elements with no fixed points. sum Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' super Typically used to call a cooperative superclass method. symbolic_expression sys This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter. tan The tangent function. tanh The hyperbolic tangent function. taylor Expands self in a truncated Taylor or Laurent series in the variable v around the point a, containing terms through (x - a)^n. transpose trial_division Return the smallest prime divisor <= bound of the positive integer n, or n if there is no such prime. two_squares Write the integer n as a sum of two integer squares if possible; otherwise raise a ValueError. type Returns an object's type. union Return the union of x and y, as a list. uniq Return the sublist of all elements in the list x that is sorted and is such that the entries in the sublist are unique. valuation The exact power of p>0 that divides the integer m. var Create a symbolic variable with the name *s*. v1.23 - 02/17/08 SAGE For Newbies 52/150

vars Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. vector Return a vector over with given entries. version Return the version of SAGE. view Compute a latex representation of each object in objects. NOTE: In notebook mode this function simply embeds a png image in the output walltime Return the wall time. xgcd Returns triple of integers (g,s,t) such that g = s*a+t*b = gcd(a,b). xinterval Iterator over the integers between a and b, inclusive. xrange Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. zip Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. Table 3: Subset of SAGE functions

1079 3.22 Obtaining Information On SAGE Functions 1080 Table 3 includes a list of functions along with a short description of what each 1081 one does. This is not enough information, however, to show how to actually use 1082 these functions. One way to obtain additional information on any function is to 1083 type its name followed by a question mark '?' into a worksheet cell then press the 1084 key:

1085 is_even? 1086 | 1087 File: /opt/sage-2.7.1-debian-32bit-i686- 1088 Linux/local/lib/python2.5/site-packages/sage/misc/functional.py 1089 Type: 1090 Definition: is_even(x) 1091 Docstring:

1092 Return whether or not an integer x is even, e.g., divisible by 2.

1093 EXAMPLES: 1094 sage: is_even(-1) 1095 False 1096 sage: is_even(4) 1097 True 1098 sage: is_even(-2) 1099 True

1100 A gray window will then be shown which contains the following information 1101 about the function: v1.23 - 02/17/08 SAGE For Newbies 53/150

1102 File: Gives the name of the file that contains the source code that implements 1103 the function. This is useful if you would like to locate the file to see how the 1104 function is implemented or to edit it.

1105 Type: Indicates the type of the object that the name passed to the information 1106 service refers to.

1107 Definition: Shows how the function is called.

1108 Docstring: Displays the documentation string that has been placed into the 1109 source code of this function.

1110 You may obtain help on any of the functions listed in Table 3, or the SAGE 1111 reference manual, using this technique. Also, if you place two question marks 1112 '??' after a function name and press the key, the function's source code 1113 will be displayed.

1114 3.23 Information Is Also Available On User-Entered 1115 Functions 1116 The information service can also be used to obtain information on user-entered 1117 functions and a better understanding of how the information service works can 1118 be gained by trying this at least once.

1119 If you have not already done so in your current worksheet, type in the addnums 1120 function again and execute it:

1121 def addnums(num1, num2): 1122 """ 1123 Returns the sum of num1 and num2. 1124 """ 1125 answer = num1 + num2 1126 return answer

1127 #Call the function and have it add 2 to 3. 1128 a = addnums(2, 3) 1129 print a 1130 | 1131 5

1132 Then obtain information on this newly-entered function using the technique from 1133 the previous section:

1134 addnums? 1135 | v1.23 - 02/17/08 SAGE For Newbies 54/150

1136 File: /home/sage/sage_notebook/worksheets/root/9/code/8.py 1137 Type: 1138 Definition: addnums(num1, num2) 1139 Docstring:

1140 Returns the sum of num1 and num2.

1141 This shows that the information that is displayed about a function is obtained 1142 from the function's source code.

1143 3.24 Examples Which Use Functions Included With SAGE 1144 The following short programs show how some of the functions listed in Table 3 1145 are used: 1146 1147 #Determine the sum of the numbers 1 through 10. 1148 add([1,2,3,4,5,6,7,8,9,10]) 1149 | 1150 55

1151 #Cosine of 1 radian. 1152 cos(1.0) 1153 | 1154 0.540302305868140

1155 #Determine the denominator of 15/64. 1156 denominator(15/64) 1157 | 1158 64

1159 #Obtain a list that contains all positive 1160 #integer divisors of 20. 1161 divisors(20) 1162 | 1163 [1, 2, 4, 5, 10, 20]

1164 #Determine the greatest common divisor of 40 and 132. 1165 gcd(40,132) 1166 | 1167 4

1168 #Determine the product of 2, 3, and 4. 1169 mul([2,3,4]) 1170 | 1171 24

1172 #Determine the length of a list. v1.23 - 02/17/08 SAGE For Newbies 55/150

1173 a = [1,2,3,4,5,6,7] 1174 len(a) 1175 | 1176 7

1177 #Create a list which contains the integers 0 through 10. 1178 a = srange(11) 1179 a 1180 | 1181 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1182 #Create a list which contains real numbers between 1183 #0.0 and 10.5 in steps of .5. 1184 a = srange(11,step=.5) 1185 a 1186 | 1187 [0.0000000, 0.5000000, 1.000000, 1.500000, 2.000000, 2.500000, 1188 3.000000, 3.500000, 4.000000, 4.500000, 5.000000, 5.500000, 1189 6.000000, 6.500000, 7.000000, 7.500000, 8.000000, 8.500000, 1190 9.000000, 9.500000, 10.00000, 10.50000]

1191 #Create a list which contains the integers -5 through 5. 1192 a = srange(-5,6) 1193 a 1194 | 1195 [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]

1196 #The zip() function takes multiple sequences and groups 1197 #parallel members inside tuples in an output list. One 1198 #application this is useful for is creating points from 1199 #table data so they can be plotted. 1200 a = [1,2,3,4,5] 1201 b = [6,7,8,9,10] 1202 c = zip(a,b) 1203 c 1204 | 1205 [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

1206 3.25 Using srange() And zip() With The for Statement 1207 Instead of manually creating a sequence for use by a for statement, srange() can 1208 be used to create the sequence automatically:

1209 for t in srange(6): 1210 print t, 1211 | v1.23 - 02/17/08 SAGE For Newbies 56/150

1212 0 1 2 3 4 5

1213 The for statement can also be used to loop through multiple sequences in 1214 parallel using the zip() function:

1215 t1 = (0,1,2,3,4) 1216 t2 = (5,6,7,8,9) 1217 for (a,b) in zip(t1,t2): 1218 print a,b 1219 | 1220 0 5 1221 1 6 1222 2 7 1223 3 8 1224 4 9

1225 3.26 List Comprehensions 1226 Up to this point we have seen that if statements, for loops, lists, and 1227 functions are each extremely powerful when used individually and together. 1228 What is even more powerful, however, is a special statement called a list 1229 comprehension which allows them to be used together with a minimum amount 1230 of syntax.

1231 Here is the simplified syntax for a list comprehension:

1232 [ expression for variable in sequence [if condition] ]

1233 What a list comprehension does is to loop through a sequence placing each 1234 sequence member into the specified variable in turn. The expression also 1235 contains the variable and, as each member is placed into the variable, the 1236 expression is evaluated and the result is placed into a new list. When all of the 1237 members in the sequence have been processed, the new list is returned.

1238 In the following example, t is the variable, 2*t is the expression, and [1,2,3,4,5] 1239 is the sequence:

1240 a = [2*t for t in [0,1,2,3,4,5]] 1241 a 1242 | 1243 [0, 2, 4, 6, 8, 10]

1244 Instead of manually creating the sequence, the srange() function is often used to 1245 create it automatically: v1.23 - 02/17/08 SAGE For Newbies 57/150

1246 a = [2*t for t in srange(6)] 1247 a 1248 | 1249 [0, 2, 4, 6, 8, 10]

1250 An optional if statement can also be used in a list comprehension to filter the 1251 results that are placed in the new list:

1252 a = [b^2 for b in range(20) if b % 2 == 0] 1253 a 1254 | 1255 [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

1256 In this case, only results that are evenly divisible by 2 are placed in the output 1257 list. v1.23 - 02/17/08 SAGE For Newbies 58/150

1258 4 Object Oriented Programming 1259 The purpose of this chapter is to introduce the main concepts behind how 1260 object oriented SAGE code works and how it is used to solve problems. It 1261 assumes that you have little or no Object Oriented Programming (OOP) 1262 experience and it is going to give you enough of an understanding of OOP so that 1263 you can more effectively use SAGE objects to solve problems.

1264 Do not worry too much if this OOP stuff does not completely sink in right away 1265 because you can use SAGE objects to solve problems without yet having the skill 1266 needed to program objects from scratch yourself. Having said that, this chapter 1267 does show how to program an object from scratch so you can better understand 1268 how SAGE's pre-built objects work.

1269 4.1 Object Oriented Mind Re-wiring 1270 In my opinion, one of the more difficult things you will do in the area of 1271 programming is to make the mental switch from the procedural programming 1272 paradigm to the object oriented programming paradigm. The problem is not that 1273 object oriented programming is necessarily more difficult than procedural 1274 programming. The problem is that it is so different in its approach to solving 1275 programming problems that some mental re-wiring is going to have to happen 1276 before you truly "get it". This mental re-wiring is a process that happens very 1277 slowly as you write object oriented programs and dig deeper into object oriented 1278 books in an effort to really understand what OOP is all about.

1279 Right from the beginning you will see that there is something very special and 1280 powerful going on, but it will elude your efforts to firmly it. When you do 1281 finally "get it" it will usually not come all at once like a bright light going on. It is 1282 more like a dim light that you can sense glowing in the back of your mind that 1283 brightens very slowly. For each new programming problem you encounter, the 1284 front part of your mind will still produce a procedural plan to solve it. However 1285 you will begin to notice that this glow in the back of your mind will present 1286 object oriented strategies (dim at first, but slowly increasing in clarity) that will 1287 also solve the problem and these object oriented strategies are so interesting 1288 that over time you will find yourself paying more and more attention to them. 1289 Eventually a time will come when many programming problems will trigger the 1290 production of rich object oriented strategies for solving them from the now 1291 bright object oriented part of your mind.

1292 4.2 Attributes And Behaviors 1293 Object oriented programming is a software design philosophy where software is 1294 made to work similar to the way that objects in the physical world work. All 1295 physical objects have attributes and behaviors. One example is a typical office 1296 chair which has color, number of wheels, and material type as attributes and v1.23 - 02/17/08 SAGE For Newbies 59/150

1297 spin, roll, and set height as behaviors.

1298 Software objects are made to work like physical objects and so they also have 1299 attributes and behaviors. A software object's attributes are held in special 1300 variables called instance variables and its behaviors are determined by code 1301 which is held in methods (which are also called member functions). Methods 1302 are similar to standard functions except they are associated with objects instead 1303 of "floating around free". In SAGE, instance variables and methods are often 1304 referred to as just attributes.

1305 After an object is created, it is used by sending it messages, which means to 1306 call or invoke its methods. In the case of the chair, we could imagine sending it 1307 a chair.spin(3) message which would tell the chair to spin 3 times, or a 1308 chair.setHeight(32) message which would tell the chair to set its height to 32 1309 centimeters.

1310 4.3 Classes (Blueprints That Are Used To Create Objects) 1311 A class can be thought of as a blueprint that is used to construct objects and it 1312 is conceptually similar to a house blueprint. An architect uses a blueprint to 1313 precisely define exactly how a given house should be constructed, what materials 1314 should be used, what its various dimensions should be, etc. After the blueprint is 1315 finished, it can be used to construct one house or many houses because the 1316 blueprint contains the information that describes how to create a house, it is not 1317 the house itself. A creating a class is very similar to an architect 1318 creating a house blueprint except that the architect uses a drafting table or a 1319 CAD system to develop a blueprint while a programmer uses a text editor or an 1320 IDE (Integrated Development Environment) to develop a class.

1321 4.4 Object Oriented Programs Create And Destroy Objects 1322 As Needed 1323 The following analogy describes how software objects are created and destroyed 1324 as needed in object oriented program. Creating an object is also called 1325 instantiating it because the class (blueprint) that defines the object is being 1326 used to create an object instance. The act of destroying an object and reclaiming 1327 the memory and other resources it was using is called garbage collection.

1328 Imagine that a given passenger jet can operate in a manner which is similar an 1329 object oriented program and that the jet is being prepared to fly across the 1330 Atlantic ocean from New York to London. Just before takeoff, the blueprints for 1331 every part of the aircraft are brought to the tarmac and given to a team of 1332 workers who will use them to very quickly construct all of the components 1333 needed to build the aircraft. As each component is constructed, it is attached to 1334 the proper place on the aircraft and in a short time the aircraft is complete and 1335 ready to use. The passengers are loaded onto the jet and and it takes off. v1.23 - 02/17/08 SAGE For Newbies 60/150

1336 After the plane leaves the ground, the landing gear are disintegrated (garbage 1337 collected) because they are not needed during the flight and hauling them across 1338 the Atlantic ocean would just waste costly fuel. There is no need to worry, 1339 however, because the landing gear will be reconstructed using the proper 1340 blueprints (classes) just before landing in London

1341 A few minutes after takeoff the pilot receives notification that the company that 1342 manufactured the aircraft's jet engines has just released a new model that is 1343 15% more fuel efficient than the ones that the aircraft is currently using and the 1344 airline is going to upgrade the aircraft's engines while the plane is in flight. The 1345 airline sends the blueprints for the new engines over the network to the plane 1346 and these are used to construct (instantiate) three of the new engines. After the 1347 new engines are constructed, the three old engines are shut down one at a time, 1348 replaced with a new engine, and disintegrated. The engine upgrade goes 1349 smoothly and the passengers are not even aware that the upgrade took place.

1350 This flight just happens to have an important world figure on board and halfway 1351 through the flight a hostile aircraft is encountered which orders our pilot to 1352 change his course. Instead of complying with this demand, however, the pilot 1353 retrieves a set of blueprints from the blueprint library for a 50mm machine gun 1354 turret, has 4 of these turrets constructed , and then has them attached to the 1355 plane's top, bottom, nose, and tail sections. A few blasts from one of these guns 1356 is enough to deter the hostile aircraft and it quickly moves away, eventually 1357 dropping off of the radar screen. The rest of the flight is uneventful. As the 1358 aircraft approaches London, the machine gun turrets are disintegrated, a new 1359 set of landing gear are constructed using the landing gear blueprints, and the 1360 plane safely lands. After the passengers are in the terminal, the whole plane is 1361 disintegrated.

1362 4.5 Object Oriented Program Example 1363 The following two sections cover a simple object oriented program called Hellos. 1364 The first section presents a version of the program which does not contain any 1365 comments so the code itself is easier to see. The second section contains a fully- 1366 commented version of the program along with a detailed description of how the 1367 program works.

4.5.1 Hellos Object Oriented Program Example (No Comments)

1368 class Hellos:

1369 def __init__(self, mess): 1370 self.message = mess v1.23 - 02/17/08 SAGE For Newbies 61/150

1371 def print_message(self): 1372 print"The message is: ", self.message 1373 1374 def say_goodbye(self): 1375 print "Goodbye!" 1376 1377 def print_hellos(self, total): 1378 count = 1 1379 while count <= total: 1380 print"Hello ", count 1381 count = count + 1

1382 print " "

1383 1384 obj1 = Hellos("Are you having fun yet?") 1385 obj2 = Hellos("Yes I am!")

1386 obj1.print_message() 1387 obj2.print_message() 1388 print " "

1389 obj1.print_hellos(3) 1390 obj2.print_hellos(5)

1391 obj1.say_goodbye() 1392 obj2.say_goodbye() 1393 | 1394 The message is: Are you having fun yet? 1395 The message is: Yes I am! 1396 1397 Hello 1 1398 Hello 2 1399 Hello 3 1400 1401 Hello 1 1402 Hello 2 1403 Hello 3 1404 Hello 4 1405 Hello 5 1406 1407 Goodbye! 1408 Goodbye!

1409 4.5.2 Hellos Object Oriented Program Example (With v1.23 - 02/17/08 SAGE For Newbies 62/150

1410 Comments) 1411 We will now look at the Hellos program in more detail. This version of the 1412 program has had comments added to it. The line numbers and colons on the left 1413 side of the program are not part of the program itself and they have been added 1414 to make referencing different parts of the program easier.

1415 1:class Hellos: 1416 2: """ 1417 3: Hellos is a 'class' and a class is a blueprint for creating 1418 4: objects. Classes consist of instance variables (attributes) 1419 5: and methods (behaviors). 1420 6: """ 1421 7: 1422 8: def __init__(self, mess): 1423 9: """ 1424 10: __init__ is a special kind of built-in method called a 1425 11: constructor. A constructor method is only invoked once 1426 12: when an object is being created and its job is to complete 1427 13: the construction of the object. After the object has 1428 14: been created its constructors are no longer used. The 1429 15: purpose of this constructor is to create an instance 1430 16: variable called 'message' and then initialize it with a 1431 17: string. 1432 18: """ 1433 19: 1434 20: """ 1435 21: This code creates an instance variable. Every object 1436 22: instance created from this class 'blueprint' will have 1437 23: its own unique copy of any instance variables. Instance 1438 24: variables hold an object's attributes (or state). 1439 25: The self variable here holds a reference to the current 1440 26: object. 1441 27: """ 1442 28: self.message = mess; 1443 29: 1444 30: 1445 31: 1446 32: def print_message(self): 1447 33: """ 1448 34: print_message is an instance method that gives objects 1449 35: created using this class their 'print message' behavior. 1450 36: """ 1451 37: print"The message is: ", self.message 1452 38: 1453 39: 1454 40: v1.23 - 02/17/08 SAGE For Newbies 63/150

1455 41: def say_goodbye(self): 1456 42: """ 1457 43: say_goodbye is an instance method that gives objects 1458 44: created using this class their 'say goodby' behavior. 1459 45: """ 1460 46: print "Goodbye!" 1461 47: 1462 48: 1463 49: 1464 50: def print_hellos(self, total): 1465 51: """ 1466 52: print_hellos is an instance method that takes the number 1467 53: of Hellos to print as an argument and it prints this many 1468 54: Hellos to the screen. 1469 55: """ 1470 56: count = 1 1471 57: while count <= total: 1472 58: print"Hello ", count 1473 59: count = count + 1 1474 60: 1475 61: print " " 1476 62: 1477 63: 1478 64:""" 1479 65:The following code creates two separate Hellos objects (instances) 1480 66:which are referenced by the variables obj1 and obj2 respectively. 1481 67:A unique String parameter is passed to each object when it is 1482 68:instantiated and this String is used to initialize the object's 1483 69:state. 1484 70: 1485 71:After the objects are created, messages are sent to them by 1486 72:calling their methods in order to have them perform behaviors. 1487 73:This is done by 'picking an object up' by its reference (lets 1488 74:say obj1) placing a dot after this reference and then typing the 1489 75:name of an object's method that you want to invoke. 1490 76:""" 1491 77: 1492 78:obj1 = Hellos("Are you having fun yet?") 1493 79:obj2 = Hellos("Yes I am!") 1494 80: 1495 81:obj1.print_message() 1496 82:obj2.print_message() 1497 83:print " " 1498 84: 1499 85:obj1.print_hellos(3) 1500 86:obj2.print_hellos(5) 1501 87: v1.23 - 02/17/08 SAGE For Newbies 64/150

1502 88:obj1.say_goodbye() 1503 89:obj2.say_goodbye()

1504 On line 1 the class Hellos is defined using a class statement and by convention 1505 class names start with a capital letter. If the class name consists of multiple 1506 words, then the first letter of each word is capitalized and all other letters are 1507 typed in lower case (for example, HelloWorld). The class begins on line 1 and 1508 ends on line 61, which is the last line of indented code it contains. All methods 1509 and instance variables that are part of a class need to be inside the class's 1510 indented code block.

1511 The Hellos class contains one constructor method on line 8, one instance 1512 variable which is created on line 28, and three instance methods on lines 32, 1513 41, and 50 respectively. The purpose of instance variables are to give an object 1514 unique attributes that differentiate it from other objects that are created from a 1515 given class The purpose of instance methods are to give each object its 1516 behaviors. All methods in an object have access to that object's instance 1517 variables and these instance variables can be accessed by the code in these 1518 methods. Instance variable names follow the same convention that function 1519 names do.

1520 The method on line 8 is a special method called a constructor. A constructor 1521 method is only invoked when an object is being created and its purpose is to 1522 complete the construction of the object. After the object has been created, its 1523 constructor is no longer used. The purpose of the constructor on line 8 is to 1524 initialize each Hellos object's message instance variable with a string that is 1525 passed to it when a new object of type Hellos is created (see lines 78 and 79).

1526 All instance methods have an argument passed to them which contains a 1527 reference to the specific object that the method was called from. This argument 1528 is always placed into the leftmost argument position and, by convention, the 1529 variable that is placed in this position is called self. The self variable is then 1530 used to create and access that specific object's instance variables.

1531 On line 28, the code self.message = mess takes the object that was passed into 1532 the constructor's mess variable and assigns it to an instance variable called 1533 message. An instance variable is created via assignment just like normal 1534 variables are. The dot operator '.' is used to access an object's instance 1535 variables by placing it between a variable which holds a reference to the object 1536 and the instance variable's name (like self.message or obj1.message).

1537 The methods on lines 32, 41, and 50 give objects created using the Hellos class 1538 their behaviors. The print_message() method provides the behavior of printing 1539 the string that is present in the object's message instance variable and the 1540 say_goodbye() method provides the behavior of printing the string "Goodbye!" 1541 The print_hellos() method takes an integer number as a parameter and it prints v1.23 - 02/17/08 SAGE For Newbies 65/150

1542 the word 'Hello' that many times. The naming convention for methods is the 1543 same as the one used for function names.

1544 The code below the Hellos class creates two separate objects (instances) which 1545 are then assigned to the variables obj1 and obj2 respectively. An object is 1546 created by typing its class name followed by a pair of parentheses. Any 1547 arguments that are placed within the parentheses will be passed to the 1548 constructor method.

1549 When the Hellos class is called, a string is passed to its constructor method and 1550 this string is used to initialize the object's state. An object's state is determined 1551 by the contents of its instance variables. If any of an object's instance variables 1552 are changed, then the object's state has been changed too. Since Hellos objects 1553 only have one instance variable called message, their state is determined by this 1554 variable.

1555 After objects are created, their behaviors are requested by calling their methods. 1556 This is done by "picking an object up" by a variable that references it (lets say 1557 obj1), placing a dot after this variable, and then typing the name of one of the 1558 object's methods that you want to invoke, followed by its arguments in 1559 parentheses.

1560 4.6 SAGE Classes And Objects 1561 While SAGE's functions contain many capabilities, most of SAGE's capabilities 1562 are contained in classes and the objects that are instantiated from these 1563 classes. SAGE's classes and objects represent a significant amount of 1564 information which will take a while to explain. However, the easier material will 1565 be presented first so that you can start working with SAGE objects as soon as 1566 possible.

1567 4.7 Obtaining Information On SAGE Objects 1568 Type the following code into a cell and execute it:

1569 x = 5 1570 print type(x) 1571 | 1572

1573 We have already used the type() function to determine the type of an integer, but 1574 now we can explain what a type is in more detail. Enter 1575 sage.rings.integer.Integer followed by a question mark '?' into a new cell and 1576 then press the key:

1577 sage.rings.integer.Integer? v1.23 - 02/17/08 SAGE For Newbies 66/150

1578 | 1579 File:/opt/sage-2.7.1-debian-32bit-i686- 1580 Linux/local/lib/python2.5/site-packages/sage/rings/integer.so 1581 Type: 1582 Definition: sage.rings.integer.Integer([noargspec])

1583 Docstring:

1584 The class{Integer} class represents arbitrary precision 1585 integers. It derives from the class{Element} class, so 1586 integers can be used as ring elements anywhere in SAGE.

1587 begin{notice} 1588 The class class{Integer} is implemented in Pyrex, 1589 as a wrapper of the GMP mpz_t integer type. 1590 end{notice}

1591 This information indicates that sage.rings.integer.Integer is really a class that is 1592 able to create Integer objects. Also, if you place two questions marks '??' after a 1593 class name and press the key, the class's source code will be displayed.

1594 Now, in a separate cell type x. and then press the key:

1595 x. 1596 | 1597 x.additive_order x.gcd x.numerator 1598 x.base_base_extend x.inverse_mod x.ord 1599 x.inverse_of_unit x.order x.parent 1600 x.base_extend x.is_nilpotent x.plot 1601 x.base_extend_canonical x.is_one x.powermodm_ui 1602 x.is_perfect_power x.powermod x.quo_rem 1603 x.base_extend_recursive x.is_power x.rename 1604 x.base_ring x.is_power_of x.reset_name 1605 x.binary x.is_prime x.save 1606 x.category x.is_prime_power x.set_si 1607 x.ceil x.is_pseudoprime x.set_str 1608 x.coprime_integers x.is_square x.sqrt 1609 x.crt x.is_squarefree x.sqrt_approx 1610 x.db x.is_unit x.square_free_part 1611 x.degree x.is_zero x.str 1612 x.denominator x.isqrt x.substitute 1613 x.digits x.jacobi x.test_bit 1614 x.div x.kronecker x.val_unit 1615 x.lcm x.subs x.valuation 1616 x.divides x.leading_coefficient x.version 1617 x.dump x.list x.xgcd 1618 x.dumps x.mod x.parent v1.23 - 02/17/08 SAGE For Newbies 67/150

1619 x.exact_log x.multiplicative_order x.plot 1620 x.factor x.next_prime x.rename 1621 x.factorial x.next_probable_prime x.reset_name 1622 x.floor x.nth_root x.powermodm_ui

1623 A gray window will be displayed which contains all of the methods that the object 1624 contains. If any of these methods is selected with the mouse, its name will be 1625 placed into the cell after the dot operator as a convenience. For now, select the 1626 is_prime method. When its name is placed into the cell, type a question mark '?' 1627 after it and press the key in order to obtain information on this method:

1628 x.is_prime? 1629 | 1630 File: /opt/sage-2.7.1-debian-32bit-i686-Linux/local/lib/python/ 1631 site-packages/sage/rings/integer/pyx 1632 Type: 1633 Definition: x.is_prime()

1634 Docstring:

1635 Retuns True if self is prime

1636 EXAMPLES: 1637 sage: z = 2^31 - 1 1638 sage: z.is_prime() 1639 True 1640 sage: z = 2^31 1641 sage: z.is_prime() 1642 False

1643 The Definition section indicates that the is_prime() method is called without 1644 passing any arguments to it and the Docstring section indicates that the method 1645 will return True if the object is prime. The following code shows the variable x 1646 (which still contains 5) being used to call the is_prime() method:

1647 x.is_prime() 1648 | 1649 True

1650 4.8 The List Object's Methods 1651 Lists are objects and therefore they contain methods that provide useful 1652 capabilities:

1653 a = [] 1654 a. v1.23 - 02/17/08 SAGE For Newbies 68/150

1655 | 1656 a.append a.extend a.insert a.remove a.sort 1657 a.count a.index a.pop a.reverse

1658 The following programs demonstrate some of a list object's methods:

1659 # Append an object to the end of a list. 1660 a = [1,2,3,4,5,6] 1661 print a 1662 a.append(7) 1663 print a 1664 | 1665 [1, 2, 3, 4, 5, 6] 1666 [1, 2, 3, 4, 5, 6, 7]

1667 # Insert an object into a list. 1668 a = [1,2,4,5] 1669 print a 1670 a.insert(2,3) 1671 print a 1672 | 1673 [1, 2, 4, 5] 1674 [1, 2, 3, 4, 5]

1675 # Sort the contents of a list. 1676 a = [8,2,7,1,6,4] 1677 print a 1678 a.sort() 1679 print a 1680 | 1681 [8, 2, 7, 1, 6, 4] 1682 [1, 2, 4, 6, 7, 8]

1683 4.9 Extending Classes With Inheritence 1684 Object technologies are subtle and powerful. They possess a number of 1685 mechanisms for dealing with complexity and class inheritance is one of them. 1686 Class inheritance is the ability of a class to obtain or inherit all of the instance 1687 variables and methods of another class (called a parent class, super class, or 1688 base class) using a minimal amount of code. A class that inherits from a parent 1689 class is called a child class or sub class. This means that a child class can do 1690 everything its parent can do along with any additional functionality that is 1691 programmed into the child.

1692 The following program demonstrates class inheritance by having a Person class 1693 inherit from the built-in object class and having an ArmyPrivate class inherit v1.23 - 02/17/08 SAGE For Newbies 69/150

1694 from the Person class:

1695 class Person(object): 1696 def __init__(self): 1697 self.rank = "I am just a Person, I have no rank." 1698 1699 def __str__(self): 1700 return "str: " + self.rank

1701 def __repr__(self): 1702 return "repr: " + self.rank

1703 class ArmyPrivate(Person): 1704 def __init__(self): 1705 self.rank = "ArmyPrivate."

1706 a = object() 1707 print type(a)

1708 b = Person() 1709 print type(b)

1710 c = ArmyPrivate() 1711 print type(c) 1712 | 1713 1714 1715

1716 After the classes have been created, this program instantiates an object of type 1717 object which is assigned to variable 'a', an object of type Person which is 1718 assigned to variable 'b', and an object of type ArmyPrivate which is assigned to 1719 variable 'c'.

1720 The following code can be used to display the inheritance hierarchy of any 1721 object. If it is executed in a separate cell after the above program has been 1722 executed, the inheritance hierarchy of the ArmyPrivate class is displayed (don't 1723 worry about trying to understand how this code works. Just use it for 1724 now.):

1725 #Display the inheritance hierarchy of an object. Note: don't worry 1726 #about trying to understand how this program works. Just use it for 1727 #now. 1728 def class_hierarchy(cls, indent): v1.23 - 02/17/08 SAGE For Newbies 70/150

1729 print '.'*indent, cls 1730 for supercls in cls.__bases__: 1731 class_hierarchy(supercls, indent+1)

1732 def instance_hierarchy(inst): 1733 print 'Inheritance hierarchy of', inst 1734 class_hierarchy(inst.__class__, 3)

1735 z = ArmyPrivate()

1736 instance_hierarchy(z) 1737 | 1738 Inheritance hierarchy of str: ArmyPrivate 1739 ... 1740 .... 1741 .....

1742 The instance_hierarchy function will display the inheritance hierarchy of any 1743 object that is passed to it. In this case, an ArmyPrivate object was instantiated 1744 and passed to the instance_hierarchy function and the object's inheritance 1745 hierarchy was displayed. Notice that the topmost class in the hierarchy, which is 1746 the object class, was printed last and that Person inherits from object and 1747 ArmyPrivate inherits from Person.

1748 4.10 The object Class, The dir() Function, And Built-in 1749 Methods 1750 The object class is built into SAGE and it contains a small number of useful 1751 methods. These methods are so useful that many SAGE classes inherit from the 1752 object class either 1) directly or 2) indirectly by inheriting from a class that 1753 inherits from the object class. Lets begin our discussion of the inheritance 1754 program by looking at the methods that are included in the object class. The 1755 dir() function lists all of an object's attributes (which means both its instance 1756 variables and its methods) and we can use it to see which methods an object of 1757 type object contains:

1758 dir(a) 1759 | 1760 ['__class__', '__delattr__', '__doc__', 1761 '__getattribute__','__hash__','__init__', '__new__', '__reduce__', 1762 '__reduce_ex__', '__repr__','__setattr__', '__str__']

1763 Names which begin and end with double underscores '__' are part of SAGE and 1764 the underscores make it unlikely that these names will conflict with programmer 1765 defined names. The Person class inherits all of these attributes from the object 1766 class, but it only uses some of them. When a method is inherited from a parent v1.23 - 02/17/08 SAGE For Newbies 71/150

1767 class, the child class can either use the parent's implementation of that method 1768 or it can redefine it so that it behaves differently than the parent's version.

1769 As discussed earlier, the __init__ method is a constructor and it helps to complete 1770 construction of each new object that is created using the class it is in. The 1771 Person class redefines the __init__ method so that it creates an instance variable 1772 called rank and assigns the string "I am just a Person, I have no rank" to it.

1773 The __ repr__ and __str__ methods are also redefined in the Person class. The 1774 __repr__ method returns a string representation of the object it is a part of:

1775 b 1776 | 1777 repr: I am just a Person, I have no rank. 1778

1779 The __str__ function also returns a string representation of the object it is a part 1780 of, but only when it is passed to statements like print:

1781 print b 1782 | 1783 str: I am just a Person, I have no rank.

1784 The __str__ method is usually used to provide a more user friendly string than the 1785 __repr__ method does but in this example, very similar strings are returned.

1786 4.11 The Inheritance Hierarchy Of The 1787 sage.rings.integer.Integer Class 1788 The following code displays the inheritance hierarchy of the 1789 sage.rings.integer.Integer class:

1790 #Display the inheritance hierarchy of an object. Note: don't worry 1791 #about trying to understand how this program works. Just use it for 1792 #now. 1793 def class_hierarchy(cls, indent): 1794 print '.'*indent, cls 1795 for supercls in cls.__bases__: 1796 class_hierarchy(supercls, indent+1)

1797 def instance_hierarchy(inst): 1798 print 'Inheritance hierarchy of', inst 1799 class_hierarchy(inst.__class__, 3)

1800 instance_hierarchy(1) 1801 | v1.23 - 02/17/08 SAGE For Newbies 72/150

1802 Inheritance hierarchy of 1 1803 ... 1804 .... 1805 ..... 1806 ...... 1807 ...... 1808 ...... 1809 ...... 1810 ...... 1811 ...... 1812 ...... 1813 ......

1814 In the following explanation, I am going to leave out the beginning 1815 "sage.xxx.xxx..." part of the class names to save space. The output from the 1816 instance_hierarchy function indicates that the number 1 is an object of type 1817 Integer. It then shows that Integer inherits from EuclideanDomainElement, 1818 EuclideanDomainElement inherits from PrincipalIdealDomainElement, etc. 1819 At the top of the hierarchy (which is at the bottom of the list) SAGEObject 1820 inherits from object.

1821 Here is the inheritance hierarchy for two other commonly used SAGE objects:

1822 instancehierarchy(1/2) 1823 | 1824 Inheritance hierarchy of 1/2 1825 ... 1826 .... 1827 ..... 1828 ...... 1829 ...... 1830 ...... 1831 ...... 1832 ......

1833 instancehierarchy(1.2) 1834 | 1835 Inheritance hierarchy of 1.20000000000000 1836 ... 1837 .... 1838 ..... 1839 ...... 1840 ...... 1841 ...... v1.23 - 02/17/08 SAGE For Newbies 73/150

1842 4.12 The "Is A" Relationship 1843 Another aspect to the concept of inheritance is that, since a child class can do 1844 anything its parent can do, it can be used any place its parent object can be 1845 used. Take a look at the inheritance hierarchy of the Integer class. This 1846 hierarchy indicates that Integer is a EuclideanDomainElement and 1847 EuclideanDomainElement is a PrincipalIdealDomainElement and 1848 PrincipalIdealDomainElement is a DedekindDomainElement etc. until 1849 finally SAGEObject is an object (just like almost all the other classes are in 1850 SAGE since the object class is the root class from which they all descend). A 1851 more general way to look at this is to say a child class can be used any place any 1852 of its ancestor classes can be used.

1853 4.13 Confused? 1854 This chapter was probably confusing for you but again, don't worry about that. 1855 The rest of this book will contain examples which show how objects are used in 1856 SAGE and the more you see objects being used, the more comfortable you will 1857 become with them. v1.23 - 02/17/08 SAGE For Newbies 74/150

1858 5 Miscellaneous Topics

1859 5.1 Referencing The Result Of The Previous Operation 1860 When working on a problem that spans multiple cells in a worksheet, it is often 1861 desirable to reference the result of the previous operation. The underscore 1862 symbol '_' is used for this purpose as shown in the following example:

1863 2 + 3 1864 | 1865 5 1866 _ 1867 | 1868 5

1869 _ + 6 1870 | 1871 11

1872 a = _ * 2 1873 a 1874 | 1875 22

1876 5.2 Exceptions 1877 In order to assure that SAGE programs have a uniform way to handle exceptional 1878 conditions that might occur while they are running, an exception display and 1879 handling mechanism is built into the SAGE platform. This section covers only 1880 displayed exceptions because exception handling is an advanced topic that is 1881 beyond the scope of this document.

1882 The following code causes an exception to occur and information about the 1883 exception is then displayed:

1884 1/0 1885 | 1886 Exception (click to the left for traceback): 1887 ... 1888 ZeroDivisionError: Rational division by zero

1889 Since 1/0 is an undefined mathematical operation, SAGE is unable to perform the 1890 calculation. It stops execution of the program and generates an exception to 1891 inform other areas of the program or the user about this problem. If no other 1892 part of the program handles the exception, a text explanation of the exception is v1.23 - 02/17/08 SAGE For Newbies 75/150

1893 displayed. In this case, the exception informs the user that a ZeroDivisionError 1894 has occurred and that this was caused by an attempt to perform "rational 1895 division by zero".

1896 Most of the time, this is enough information for the user to locate the problem in 1897 the source code and fix it. Sometimes, however, the user needs more 1898 information in order to locate the problem and therefore the exception indicates 1899 that if the mouse is clicked to the left of the displayed exception text, additional 1900 information will be displayed:

1901 Traceback (most recent call last): 1902 File "", line 1, in 1903 File "/home/sage/sage_notebook/worksheets/tkosan/2/code/2.py", 1904 line 4, in 1905 Integer(1)/Integer(0) 1906 File "/opt/sage-2.8.3-linux-32bit-debian-4.0-i686- 1907 Linux/data/extcode/sage/", line 1, in 1908 1909 File "element.pyx", line 1471, in element.RingElement.__div__ 1910 File "element.pyx", line 1485, in element.RingElement._div_c 1911 File "integer.pyx", line 735, in integer.Integer._div_c_impl 1912 File "integer_ring.pyx", line 185, in 1913 integer_ring.IntegerRing_class._div 1914 ZeroDivisionError: Rational division by zero

1915 This additional information shows a trace of all the code in the SAGE library that 1916 was in use when the exception occurred along with the names of the files that 1917 hold the code. It allows an expert SAGE user to look at the source code if 1918 needed in order to determine if the exception was caused by a bug in SAGE or a 1919 bug in the code that was entered.

1920 5.3 Obtaining Numeric Results 1921 One sometimes needs to obtain the numeric approximate of an object and SAGE 1922 provides a number of ways to accomplish this. One way is to use the n() 1923 function and another way is to use the n() method. The following example 1924 shows both of these being used:

1925 a = 3/4 1926 print a 1927 print n(a) 1928 print a.n() 1929 | 1930 3/4 1931 0.750000000000000 1932 0.750000000000000 v1.23 - 02/17/08 SAGE For Newbies 76/150

1933 The number of digits returned can be adjusted by using the digits parameter:

1934 a = 3/4 1935 print a.n(digits=30) 1936 | 1937 0.7500000000000000000000000000000

1938 and the number of bits of precision can be adjusted by using the prec parameter:

1939 a = 4/3 1940 print a.n(prec=2) 1941 print a.n(prec=3) 1942 print a.n(prec=4) 1943 print a.n(prec=10) 1944 print a.n(prec=20) 1945 | 1946 1.5 1947 1.2 1948 1.4 1949 1.3 1950 1.3333

1951 5.4 Style Guide For Expressions 1952 Always surround the following binary operators with a single space on either 1953 side: assignment '=', augmented assignment (+=, −=, etc.), comparisons (==, <, 1954 >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

1955 Use spaces around the + and − arithmetic operators and no spaces around the 1956 * , /, %, and ^ arithmetic operators: 1957 x = x + 1 1958 x = x*3 − 5%2 1959 c = (a + b)/(a − b)

1960 Do not use spaces around the equals sign '=' when used to indicate a keyword 1961 argument or a default parameter value:

1962 a.n(digits=5)

1963 5.5 Built-in Constants 1964 SAGE has a number of mathematical constants built into it and the following is a v1.23 - 02/17/08 SAGE For Newbies 77/150

1965 list of some of the more common ones:

1966 Pi, pi: The ratio of the circumference to the diameter of a circle.

1967 E, e: Base of the natural logarithm.

1968 I, i: The imaginary unit quantity. 1969 1970 log2: The natural logarithm of the real number 2.

1971 Infinity, infinity: Can have + or − placed before it to indicate positive or 1972 negative infinity.

1973 The following examples show constants being used:

1974 a = pi.n() 1975 b = e.n() 1976 c = i.n() 1977 a,b,c 1978 | 1979 (3.14159265358979, 2.71828182845905, 1.00000000000000*I)

1980 r = 4 1981 a = 2*pi*r 1982 a,a.n() 1983 | 1984 (8*pi, 25.1327412287183)

1985 Constants in SAGE are defined as global variables and a global variable is a 1986 variable that is accessible by most SAGE code, including inside of functions and 1987 methods. Since constants are simply variables that have a constant object 1988 assigned to them, the variables can be reassigned if needed but then the 1989 constant object is lost. If one needs to have a constant reassigned to the variable 1990 it is normally associated with, the restore() function can be used. The following 1991 program shows how the variable pi can have the object 7 assigned to it and then 1992 have its default constant assigned to it again by passing its name inside of quotes 1993 to the restore() function:

1994 print pi.n()

1995 pi = 7 1996 print pi

1997 restore('pi') v1.23 - 02/17/08 SAGE For Newbies 78/150

1998 print pi.n() 1999 | 2000 3.14159265358979 2001 7 2002 3.14159265358979

2003 If the restore() function is called with no parameters, all reassigned constants 2004 are restored to their original values.

2005 5.6 Roots 2006 The sqrt() function can be used to obtain the square root of a value, but a more 2007 general technique is used to obtain other roots of a value. For example, if one 2008 wanted to obtain the cube root of 8: 3 8 2009 8 would be raised to the 1/3 power: 2010 8^(1/3) 2011 | 2012 2

2013 Due to the order of operations, the rational number 1/3 needs to be placed within 2014 parentheses in order for it to be evaluated as an exponent.

2015 5.7 Symbolic Variables 2016 Up to this point, all of the variables we have used have been created during 2017 assignment time. For example, in the following code the variable w is created 2018 and then the number 8 is assigned to it:

2019 w = 7 2020 w 2021 | 2022 7

2023 But what if you needed to work with variables that are not assigned to any 2024 specific values? The following code attempts to print the value of the variable z, 2025 but z has not been assigned a value yet so an exception is returned:

2026 print z 2027 | 2028 Exception (click to the left for traceback): 2029 ... 2030 NameError: name 'z' is not defined v1.23 - 02/17/08 SAGE For Newbies 79/150

2031 In mathematics, "unassigned variables" are used all the time. Since SAGE is 2032 mathematics oriented software, it has the ability to work with unassigned 2033 variables. In SAGE, unassigned variables are called symbolic variables and 2034 they are defined using the var() function. When a worksheet is first opened, the 2035 variable x is automatically defined to be a symbolic variable and it will remain so 2036 unless it is assigned another value in your code.

2037 The following code was executed on a newly-opened worksheet:

2038 print x 2039 type(x) 2040 | 2041 x 2042

2043 Notice that the variable x has had an object of type SymbolicVariable 2044 automatically assigned to it by the SAGE environment.

2045 If you would like to also use y and z as symbolic variables, the var() function 2046 needs to be used to do this. One can either enter var('x,y') or var('x y'). The 2047 var() function is designed to accept one or more variable names inside of a 2048 string and the names can either be separated by commas or spaces.

2049 The following program shows var() being used to initialize y and z to be 2050 symbolic variables:

2051 var('y,z') 2052 y,z 2053 | 2054 (y, z)

2055 After one or more symbolic variables have been defined, the reset() function can 2056 be used to undefine them:

2057 reset('y,z') 2058 y,z 2059 | 2060 Exception (click to the left for traceback): 2061 ... 2062 NameError: name 'y' is not defined

2063 5.8 Symbolic Expressions 2064 Expressions that contain symbolic variables are called symbolic expressions. v1.23 - 02/17/08 SAGE For Newbies 80/150

2065 In the following example, b is defined to be a symbolic variable and then it is 2066 used to create the symbolic expression 2*b:

2067 var('b') 2068 type(2*b) 2069 | 2070

2071 As can be seen by this example, the symbolic expression 2*b was placed into an 2072 object of type SymbolicArithmetic. The expression can also be assigned to a 2073 variable:

2074 m = 2*b 2075 type(m) 2076 | 2077

2078 The following program creates two symbolic expressions, assigns them to 2079 variables, and then performs operations on them:

2080 m = 2*b 2081 n = 3*b 2082 m+n, m-n, m*n, m/n 2083 | 2084 (5*b, -b, 6*b^2, 2/3)

2085 Here is another example that multiplies two symbolic expressions together:

2086 m = 5 + b 2087 n = 8 + b 2088 y = m*n 2089 y 2090 | 2091 (b + 5)*(b + 8)

5.9 Expanding And Factoring 2092 If the expanded form of the expression from the previous section is needed, it is 2093 easily obtained by calling the expand() method (this example assumes the cells 2094 in the previous section have been run):

2095 z = y.expand() 2096 z 2097 | 2098 b^2 + 13*b + 40 v1.23 - 02/17/08 SAGE For Newbies 81/150

2099 The expanded form of the expression has been assigned to variable z and the 2100 factored form can be obtained from z by using the factor() method:

2101 z.factor() 2102 | 2103 (b + 5)*(b + 8)

2104 By the way, a number can be factored without being assigned to a variable by 2105 placing parentheses around it and calling its factor() method:

2106 (90).factor() 2107 | 2108 2 * 3^2 * 5

5.10 Miscellaneous Symbolic Expression Examples

2109 var('a,b,c')

2110 (5*a + b + 4*c) + (2*a + 3*b + c) 2111 | 2112 5*c + 4*b + 7*a

2113 (a + b) - (x + 2*b) 2114 | 2115 -x - b + a

2116 3*a^2 - a*(a -5) 2117 | 2118 3*a^2 - (a - 5)*a

2119 _.factor() 2120 | 2121 a*(2*a + 5)

5.11 Passing Values To Symbolic Expressions 2122 If values are passed to a symbolic expressions, they will be evaluated and a 2123 result will be returned. If the expression only has one variable, then the value 2124 can simply be passed to it as follows:

2125 a = x^2 2126 a(5) 2127 | 2128 25 v1.23 - 02/17/08 SAGE For Newbies 82/150

2129 However, if the expression has two or more variables, each variable needs to 2130 have a value assigned to it by name:

2131 var('y') 2132 a = x^2 + y 2133 a(x=2, y=3) 2134 | 2135 7

2136 5.12 Symbolic Equations and The solve() Function 2137 In addition to working with symbolic expressions, SAGE is also able to work with 2138 symbolic equations:

2139 var('a') 2140 type(x^2 == 16*a^2) 2141 | 2142

2143 As can be seen by this example, the symbolic equation x^2 == 16*a^2 was 2144 placed into an object of type SymbolicEquation. A symbolic equation needs to 2145 use double equals '==' so that it can be assigned to a variable using a single 2146 equals '=' like this:

2147 m = x^2 == 16*a^2 2148 m, type(m) 2149 | 2150 (x^2 == 16*a^2, )

2151 Many symbolic equations can be solved algebraically using the solve() function:

2152 solve(m, a) 2153 | 2154 [a == -x/4, a == x/4]

2155 The first parameter in the solve() function accepts a symbolic equation and the 2156 second parameter accepts the symbolic variable to be solved for.

2157 The solve() function can also solve simultaneous equations:

2158 var('i1,i2,i3,v0')

2159 a = (i1 - i3)*2 + (i1 - i2)*5 + 10 - 25 == 0 2160 b = (i2 - i3)*3 + i2*1 - 10 + (i2 - i1)*5 == 0 2161 c = i3*14 + (i3 - i2)*3 + (i3 - i1)*2 - (-3*v0) == 0 v1.23 - 02/17/08 SAGE For Newbies 83/150

2162 d = v0 == (i2 - i3)*3

2163 solve([a,b,c,d], i1,i2,i3,v0) 2164 | 2165 [[i1 == 4, i2 == 3, i3 == -1, v0 == 12]]

2166 Notice that, when more than one equation is passed to solve(), they need to be 2167 placed into a list.

2168 5.13 Symbolic Mathematical Functions 2169 SAGE has the ability to define functions using mathematical syntax. The 2170 following example shows a function f being defined that uses x as a variable:

2171 f(x) = x^2 2172 f, type(f) 2173 | 2174 (x |--> x^2, 2175 )

2176 Objects created this way are of type CallableSymbolicExpression which means 2177 they can be called as shown in the following example:

2178 f(4), f(50), f(.2) 2179 | 2180 (16, 2500, 0.040000000000000010)

2181 Here is an example that uses the above CallableSymbolicExpression inside of a 2182 loop:

2183 a = 0 2184 while a <= 9: 2185 f(a) 2186 a = a + 1 2187 | 2188 0 2189 1 2190 4 2191 9 2192 16 2193 25 2194 36 2195 49 2196 64 2197 81 v1.23 - 02/17/08 SAGE For Newbies 84/150

2198 The following example accomplishes the same work that the previous example 2199 did, except it uses more advanced language features:

2200 a = srange(10) 2201 a 2202 | 2203 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2204 for num in a: 2205 f(num) 2206 | 2207 0 2208 1 2209 4 2210 9 2211 16 2212 25 2213 36 2214 49 2215 64 2216 81

2217 5.14 Finding Roots Graphically And Numerically With The 2218 find_root() Method 2219 Sometimes equations cannot be solved algebraically and the solve() function 2220 indicates this by returning a copy of the input it was passed. This is shown in the 2221 following example:

2222 f(x) = sin(x) - x - pi/2 2223 eqn = (f == 0) 2224 solve(eqn, x) 2225 | 2226 [x == (2*sin(x) - pi)/2]

2227 However, equations that cannot be solved algebraically can be solved both 2228 graphically and numerically. The following example shows the above equation 2229 being solved graphically:

2230 show(plot(f,-10,10)) 2231 | v1.23 - 02/17/08 SAGE For Newbies 85/150

2232 This graph indicates that the root for this equation is a little greater than -2.5.

2233 The following example shows the equation being solved more precisely using the 2234 find_root() method:

2235 f.find_root(-10,10) 2236 | 2237 -2.309881460010057

2238 The -10 and +10 that are passed to the find_root() method tell it the interval 2239 within which it should look for roots.

2240 5.15 Displaying Mathematical Objects In Traditional Form 2241 Earlier it was indicated that SAGE is able to display mathematical objects in 2242 either text form or traditional form. Up until this point, we have been using 2243 text form which is the default. If one wants to display a mathematical object in 2244 traditional form, the show() function can be used. The following example 2245 creates a mathematical expression and then displays it in both text form and 2246 traditional form:

2247 var('y,b,c') 2248 z = (3*y^(2*b))/(4*x^c)^2

2249 #Display the expression in text form. 2250 z 2251 | v1.23 - 02/17/08 SAGE For Newbies 86/150

2252 3*y^(2*b)/(16*x^(2*c))

2253 #Display the expression in traditional form. 2254 show(z) 2255 |

5.15.1 LaTeX Is Used To Display Objects In Traditional Mathematics Form 2256 LaTex (pronounced lā -tek, http://en.wikipedia.org/wiki/LaTeX) is a document 2257 markup language which is able to work with a wide range of mathematical 2258 symbols. SAGE objects will provide LaTeX descriptions of themselves when their 2259 latex() methods are called. The LaTeX description of an object can also be 2260 obtained by passing it to the latex() function:

2261 a = (2*x^2)/7 2262 latex(a) 2263 | 2264 \frac{{2 \cdot {x}^{2} }}{7}

2265 When this result is fed into LaTeX display software, it will generate traditional 2266 mathematics form output similar to the following:

2x2 7

2267 The jsMath package which is referenced in Drawing 2.5 is the software that the 2268 SAGE Notebook uses to translate LaTeX input into traditional mathematics form 2269 output.

2270 5.16 Sets 2271 The following example shows operations that SAGE can perform on sets:

2272 a = Set([0,1,2,3,4]) 2273 b = Set([5,6,7,8,9,0]) 2274 a,b 2275 | 2276 ({0, 1, 2, 3, 4}, {0, 5, 6, 7, 8, 9})

2277 a.cardinality() 2278 | v1.23 - 02/17/08 SAGE For Newbies 87/150

2279 5

2280 3 in a 2281 | 2282 True

2283 3 in b 2284 | 2285 False

2286 a.union(b) 2287 | 2288 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

2289 a.intersection(b) 2290 | 2291 {0} v1.23 - 02/17/08 SAGE For Newbies 88/150

2292 6 2D Plotting

2293 6.1 The plot() And show() Functions 2294 SAGE provides a number of ways to generate 2D plots of mathematical functions 2295 and one of these ways is to use the plot() function in conjunction with the 2296 show() function. The following example shows a symbolic expression being 2297 passed to the plot() function as its first parameter. The second parameter 2298 indicates where plotting should begin on the X axis and the third parameter 2299 indicates where plotting should end:

2300 a = x^2 2301 b = plot(a, 0, 10) 2302 type(b) 2303 | 2304

2305 Notice that the plot() function does not display the plot. Instead, it creates an 2306 object of type sage.plot.plot.Graphics and this object contains the plot data. The 2307 show() function can then be used to display the plot:

2308 show(b) 2309 |

2310 The show() function has 4 parameters called xmin, xmax, ymin, and ymax that 2311 can be used to adjust what part of the plot is displayed. It also has a figsize v1.23 - 02/17/08 SAGE For Newbies 89/150

2312 parameter which determines how large the image will be. The following example 2313 shows xmin and xmax being used to display the plot between 0 and .05 on the X 2314 axis. Notice that the plot() function can be used as the first parameter to the 2315 show() function in order to save typing effort (Note: if any other symbolic 2316 variable other than x is used, it must first be declared with the var() function):

2317 v = 400*e^(-100*x)*sin(200*x) 2318 show(plot(v,0,.1),xmin=0, xmax=.05, figsize=[3,3]) 2319 |

2320 The ymin and ymax parameters can be used to adjust how much of the y axis is 2321 displayed in the above plot:

2322 show(plot(v,0,.1),xmin=0, xmax=.05, ymin=0, ymax=100, figsize=[3,3]) 2323 | v1.23 - 02/17/08 SAGE For Newbies 90/150

6.1.1 Combining Plots And Changing The Plotting Color 2324 Sometimes it is necessary to combine one or more plots into a single plot. The 2325 following example combines 6 plots using the show() function:

2326 var('t') 2327 p1 = t/4E5 2328 p2 = (5*(t - 8)/2 - 10)/1000000 2329 p3 = (t - 12)/400000 2330 p4 = 0.0000004*(t - 30) 2331 p5 = 0.0000004*(t - 30) 2332 p6 = -0.0000006*(6 - 3*(t - 46)/2)

2333 g1 = plot(p1,0,6,rgbcolor=(0,.2,1)) 2334 g2 = plot(p2,6,12,rgbcolor=(1,0,0)) 2335 g3 = plot(p3,12,16,rgbcolor=(0,.7,1)) 2336 g4 = plot(p4,16,30,rgbcolor=(.3,1,0)) 2337 g5 = plot(p5,30,36,rgbcolor=(1,0,1)) 2338 g6 = plot(p6,36,50,rgbcolor=(.2,.5,.7))

2339 show(g1+g2+g3+g4+g5+g6,xmin=0, xmax=50, ymin=-.00001, ymax=.00001) 2340 |

2341 Notice that the color of each plot can be changed using the rgbcolor parameter. 2342 RGB stands for Red, Green, and Blue and the tuple that is assigned to the 2343 rgbcolor parameter contains three values between 0 and 1. The first value 2344 specifies how much red the plot should have (between 0 and 100%), the second 2345 value specifies how much green the plot should have, and the third value 2346 specifies how much blue the plot should have. v1.23 - 02/17/08 SAGE For Newbies 91/150

6.1.2 Combining Graphics With A Graphics Object 2347 It is often useful to combine various kinds of graphics into one image. In the 2348 following example, 6 points are plotted along with a text label for each plot: 2349 """ 2350 Plot the following points on a graph:

2351 A (0,0) 2352 B (9,23) 2353 C (-15,20) 2354 D (22,-12) 2355 E (-5,-12) 2356 F (-22,-4) 2357 """

2358 #Create a Graphics object which will be used to hold multiple 2359 # graphics objects. These graphics objects will be displayed 2360 # on the same image. 2361 g = Graphics()

2362 #Create a list of points and add them to the graphics object. 2363 points=[(0,0), (9,23), (-15,20), (22,-12), (-5,-12), (-22,-4)] 2364 g += point(points)

2365 #Add labels for the points to the graphics object. 2366 for (pnt,letter) in zip(points,['A','B','C','D','E','F']): 2367 g += text(letter,(pnt[0]-1.5, pnt[1]-1.5))

2368 #Display the combined graphics objects. 2369 show(g,figsize=[5,4]) 2370 | v1.23 - 02/17/08 SAGE For Newbies 92/150

2371 First, an empty Graphics object is instantiated and a list of plotted points are 2372 created using the point() function. These plotted points are then added to the 2373 Graphics object using the += operator. Next, a label for each point is added to 2374 the Graphics object using a for loop. Finally, the Graphics object is displayed in 2375 the worksheet using the show() function.

2376 Even after being displayed, the Graphics object still contains all of the graphics 2377 that have been placed into it and more graphics can be added to it as needed. 2378 For example, if a line needed to be drawn between points C and D, the following 2379 code can be executed in a separate cell to accomplish this:

2380 g += line([(-15,20), (22,-12)]) 2381 show(g) 2382 |

2383 6.2 Advanced Plotting With matplotlib 2384 SAGE uses the matplotlib (http://matplotlib.sourceforge.net) library for its 2385 plotting needs and if one requires more control over plotting than the plot() 2386 function provides, the capabilities of matplotlib can be used directly. While a 2387 complete explanation of how matplotlib works is beyond the scope of this book, 2388 this section provides examples that should help you to begin using it. v1.23 - 02/17/08 SAGE For Newbies 93/150

6.2.1 Plotting Data From Lists With Grid Lines And Axes Labels

2389 x = [1921, 1923, 1925, 1927, 1929, 1931, 1933] 2390 y = [ .05, .6, 4.0, 7.0, 12.0, 15.5, 18.5]

2391 from matplotlib.backends.backend_agg import FigureCanvasAgg as \ 2392 FigureCanvas 2393 from matplotlib.figure import Figure 2394 from matplotlib.ticker import * 2395 fig = Figure() 2396 canvas = FigureCanvas(fig) 2397 ax = fig.add_subplot(111) 2398 ax.xaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2399 ax.yaxis.set_major_locator( MaxNLocator(10) ) 2400 ax.yaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2401 ax.yaxis.grid(True, linestyle='-', which='minor') 2402 ax.grid(True, linestyle='-', linewidth=.5) 2403 ax.set_title('US Radios Percentage Gains') 2404 ax.set_xlabel('Year') 2405 ax.set_ylabel('Radios') 2406 ax.plot(x,y, 'go-', linewidth=1.0 ) 2407 canvas.print_figure('ex1_linear.png') 2408 |

6.2.2 Plotting With A Logarithmic Y Axis v1.23 - 02/17/08 SAGE For Newbies 94/150

2409 x = [1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933] 2410 y = [ 4.61,5.24, 10.47, 20.24, 28.83, 43.40, 48.34, 50.80]

2411 from matplotlib.backends.backend_agg import FigureCanvasAgg as \ 2412 FigureCanvas 2413 from matplotlib.figure import Figure 2414 from matplotlib.ticker import * 2415 fig = Figure() 2416 canvas = FigureCanvas(fig) 2417 ax = fig.add_subplot(111) 2418 ax.xaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2419 ax.yaxis.set_major_locator( MaxNLocator(10) ) 2420 ax.yaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2421 ax.yaxis.grid(True, linestyle='-', which='minor') 2422 ax.grid(True, linestyle='-', linewidth=.5) 2423 ax.set_title('Distance in millions of miles flown by transport 2424 airplanes in the US') 2425 ax.set_xlabel('Year') 2426 ax.set_ylabel('Distance') 2427 ax.semilogy(x,y, 'go-', linewidth=1.0 ) 2428 canvas.print_figure('ex2_log.png') 2429 |

6.2.3 Two Plots With Labels Inside Of The Plot v1.23 - 02/17/08 SAGE For Newbies 95/150

2430 x = [20,30,40,50,60,70,80,90,100] 2431 y = [3690,2830,2130,1575,1150,875,735,686,650] 2432 z = [120,680,1860,3510,4780,5590,6060,6340,6520]

2433 from matplotlib.backends.backend_agg import FigureCanvasAgg as \ 2434 FigureCanvas 2435 from matplotlib.figure import Figure 2436 from matplotlib.ticker import * 2437 from matplotlib.dates import * 2438 fig = Figure() 2439 canvas = FigureCanvas(fig) 2440 ax = fig.add_subplot(111) 2441 ax.xaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2442 ax.yaxis.set_major_locator( MaxNLocator(10) ) 2443 ax.yaxis.set_major_formatter( FormatStrFormatter( '%d' )) 2444 ax.yaxis.grid(True, linestyle='-', which='minor') 2445 ax.grid(True, linestyle='-', linewidth=.5) 2446 ax.set_title('Number of trees vs. total volume of wood') 2447 ax.set_xlabel('Age') 2448 ax.set_ylabel('') 2449 ax.semilogy(x,y, 'bo-', linewidth=1.0 ) 2450 ax.semilogy(x,z, 'go-', linewidth=1.0 ) 2451 ax.annotate('N', xy=(550, 248), xycoords='figure pixels') 2452 ax.annotate('V', xy=(180, 230), xycoords='figure pixels') 2453 canvas.print_figure('ex5_log.png') 2454 | v1.23 - 02/17/08 SAGE For Newbies 96/150

2455 7 SAGE Usage Styles 2456 SAGE is an extremely flexible environment and therefore there are multiple ways 2457 to use it. In this chapter, two SAGE usage styles are discussed and they are 2458 called the Speed style and the OpenOffice Presentation style.

2459 The Speed usage style is designed to solve problems as quickly as possible by 2460 minimizing the amount of effort that is devoted to making results look good. 2461 This style has been found to be especially useful for solving end of chapter 2462 problems that are usually present in mathematics related textbooks.

2463 The OpenOffice Presentation style is designed to allow a person with no 2464 mathematical document creation skills to develop mathematical documents with 2465 minimal effort. This presentation style is useful for creating homework 2466 submissions, reports, articles, books, etc. and this book was developed using this 2467 style.

2468 7.1 The Speed Usage Style 2469 (In development...)

2470 7.2 The OpenOffice Presentation Usage Style 2471 (In development...) v1.23 - 02/17/08 SAGE For Newbies 97/150

2472 8 High School Math Problems (most of the 2473 problems are still in development)

2474 8.1 Pre-Algebra Wikipedia entry. http://en.wikipedia.org/wiki/Pre-algebra 2475 (In development...)

8.1.1 Equations Wikipedia entry. http://en.wikipedia.org/wiki/Equation 2476 (In development...)

8.1.2 Expressions Wikipedia entry. http://en.wikipedia.org/wiki/Mathematical_expression 2477 (In development...)

8.1.3 Geometry Wikipedia entry. http://en.wikipedia.org/wiki/Geometry 2478 (In development...)

8.1.4 Inequalities Wikipedia entry. http://en.wikipedia.org/wiki/Inequality 2479 (In development...)

8.1.5 Linear Functions Wikipedia entry. http://en.wikipedia.org/wiki/Linear_functions 2480 (In development...)

8.1.6 Measurement Wikipedia entry. http://en.wikipedia.org/wiki/Measurement 2481 (In development...)

8.1.7 Nonlinear Functions v1.23 - 02/17/08 SAGE For Newbies 98/150

Wikipedia entry. http://en.wikipedia.org/wiki/Nonlinear_system 2482 (In development...)

8.1.8 Number Sense And Operations Wikipedia entry. http://en.wikipedia.org/wiki/Number_sense Wikipedia entry. http://en.wikipedia.org/wiki/Operation_(mathematics) 2483 (In development...)

2484 8.1.8.1 Express an integer fraction in lowest terms 2485 """ 2486 Problem: 2487 Express 90/105 in lowest terms.

2488 Solution: 2489 One way to solve this problem is to factor both the numerator and the 2490 denominator into prime factors, find the common factors, and then 2491 divide both the numerator and denominator by these factors. 2492 """ 2493 n = 90 2494 d = 105 2495 print n,n.factor() 2496 print d,d.factor() 2497 | 2498 Numerator: 2 * 3^2 * 5 2499 Denominator: 3 * 5 * 7

2500 """ 2501 It can be seen that the factors 3 and 5 each appear once in both the 2502 numerator and denominator, so we divide both the numerator and 2503 denominator by 3*5: 2504 """ 2505 n2 = n/(3*5) 2506 d2 = d/(3*5) 2507 print "Numerator2:",n2 2508 print "Denominator2:",d2 2509 | 2510 Numerator2: 6 2511 Denominator2: 7

2512 """ 2513 Therefore, 6/7 is 90/105 expressed in lowest terms. v1.23 - 02/17/08 SAGE For Newbies 99/150

2514 This problem could also have been solved more directly by simply 2515 entering 90/105 into a cell because rational number objects are 2516 automatically reduced to lowest terms: 2517 """ 2518 90/105 2519 | 2520 6/7

8.1.9 Polynomial Functions Wikipedia entry. http://en.wikipedia.org/wiki/Polynomial_function 2521 (In development...)

2522 8.2 Algebra Wikipedia entry. http://en.wikipedia.org/wiki/Algebra_1 2523 (In development...)

8.2.1 Absolute Value Functions Wikipedia entry. http://en.wikipedia.org/wiki/Absolute_value 2524 (In development...)

8.2.2 Complex Numbers Wikipedia entry. http://en.wikipedia.org/wiki/Complex_numbers 2525 (In development...)

8.2.3 Composite Functions Wikipedia entry. http://en.wikipedia.org/wiki/Composite_function 2526 (In development...)

8.2.4 Conics Wikipedia entry. http://en.wikipedia.org/wiki/Conics 2527 (In development...)

8.2.5 Data Analysis Wikipedia entry. http://en.wikipedia.org/wiki/Data_analysis v1.23 - 02/17/08 SAGE For Newbies 100/150

2528 (In development...)

9 Discrete Mathematics: Elementary Number And Graph Theory Wikipedia entry. http://en.wikipedia.org/wiki/Discrete_mathematics 2529 (In development...)

9.1.1 Equations Wikipedia entry. http://en.wikipedia.org/wiki/Equation 2530 (In development...)

2531 9.1.1.1 Express a symbolic fraction in lowest terms 2532 """ 2533 Problem: 2534 Express (6*x^2 - b) / (b - 6*a*b) in lowest terms, where a and b 2535 represent positive integers.

2536 Solution: 2537 """

2538 var('a,b') 2539 n = 6*a^2 - a 2540 d = b - 6 * a * b 2541 print n 2542 print " ------" 2543 print d 2544 | 2545 2 2546 6 a - a 2547 ------2548 b - 6 a b

2549 """ 2550 We begin by factoring both the numerator and the denominator and then 2551 looking for common factors: 2552 """ 2553 n2 = n.factor() 2554 d2 = d.factor() 2555 print "Factored numerator:",n2.__repr__() 2556 print "Factored denominator:",d2.__repr__() 2557 | v1.23 - 02/17/08 SAGE For Newbies 101/150

2558 Factored numerator: a*(6*a - 1) 2559 Factored denominator: -(6*a - 1)*b

2560 """ 2561 At first, it does not appear that the numerator and denominator 2562 contain any common factors. If the denominator is studied further, 2563 however, it can be seen that if (1 - 6 a) is multiplied by -1, 2564 (6 a - 1) is the result and this factor is also present 2565 in the numerator. Therefore, our next step is to multiply both the 2566 numerator and denominator by -1: 2567 """ 2568 n3 = n2 * -1 2569 d3 = d2 * -1 2570 print "Numerator * -1:",n3.__repr__() 2571 print "Denominator * -1:",d3.__repr__() 2572 | 2573 Numerator * -1: -a*(6*a - 1) 2574 Denominator * -1: (6*a - 1)*b

2575 """ 2576 Now, both the numerator and denominator can be divided by (6*a - 1) 2577 in order to reduce each to lowest terms: 2578 """ 2579 common_factor = 6*a - 1 2580 n4 = n3 / common_factor 2581 d4 = d3 / common_factor 2582 print n4 2583 print " ---" 2584 print d4 2585 | 2586 - a 2587 --- 2588 b

2589 """ 2590 The problem could also have been solved more directly using a 2591 SymbolicArithmetic object: 2592 """ 2593 z = n/d 2594 z.simplify_rational() 2595 | 2596 -a/b v1.23 - 02/17/08 SAGE For Newbies 102/150

2597 9.1.1.2 Determine the product of two symbolic fractions x 2 4y 2 3 2598 Perform the indicated operation:   .  2y 3x

2599 """ 2600 Since symbolic expressions are usually automatically simplified, all 2601 that needs to be done with this problem is to enter the expression 2602 and assign it to a variable: 2603 """

2604 var('y') 2605 a = (x/(2*y))^2 * ((4*y^2)/(3*x))^3

2606 #Display the expression in text form: 2607 a 2608 | 2609 16*y^4/(27*x)

2610 #Display the expression in traditional form: 2611 show(a) 2612 |

2613 9.1.1.3 Solve a linear equation for x 2614 Solve 3x2x−8=5x−3x7

2615 """ 2616 Like terms will automatically be combined when this equation is 2617 placed into a SymbolicEquation object: 2618 """ 2619 a = 5*x + 2*x - 8 == 5*x - 3*x + 7 2620 a 2621 | 2622 7*x - 8 == 2*x + 7

2623 """ 2624 First, lets move the x terms to the left side of the equation by subtracting 2x 2625 from each side. (Note: remember that the underscore '_' holds the result of the 2626 last cell that was executed: 2627 """ v1.23 - 02/17/08 SAGE For Newbies 103/150

2628 _ - 2*x 2629 | 2630 5*x - 8 == 7

2631 """ 2632 Next, add 8 to both sides: 2633 """ 2634 _+8 2635 | 2636 5*x == 15

2637 """ 2638 Finally, divide both sides by 5 to determine the solution: 2639 """ 2640 _/5 2641 | 2642 x == 3

2643 """ 2644 This problem could also have been solved automatically using the solve() 2645 function: 2646 """ 2647 solve(a,x) 2648 | 2649 [x == 3]

2650 9.1.1.4 Solve a linear equation which has fractions 16x−13 3x5 4−x 2651 Solve = − 6 2 3

2652 """ 2653 The first step is to place the equation into a SymbolicEquation 2654 object. It is good idea to then display the equation so that you can 2655 verify that it was entered correctly: 2656 """ 2657 a = (16*x - 13)/6 == (3*x + 5)/2 - (4 - x)/3 2658 a 2659 | 2660 (16*x - 13)/6 == (3*x + 5)/2 - (4 - x)/3

2661 """ 2662 In this case, it is difficult to see if this equation has been 2663 entered correctly when it is displayed in text form so lets also 2664 display it in traditional form: v1.23 - 02/17/08 SAGE For Newbies 104/150

2665 """ 2666 show(a) 2667 |

2668 """ 2669 The next step is to determine the least common denominator (LCD) of 2670 the fractions in this equation so the fractions can be removed: 2671 """ 2672 lcm([6,2,3]) 2673 | 2674 6

2675 """ 2676 The LCD of this equation is 6 so multiplying it by 6 removes the 2677 fractions: 2678 """ 2679 b = a*6 2680 b 2681 | 2682 16*x - 13 == 6*((3*x + 5)/2 - (4 - x)/3)

2683 """ 2684 The right side of this equation is still in factored form so expand 2685 it: 2686 """ 2687 c = b.expand() 2688 c 2689 | 2690 16*x - 13 == 11*x + 7

2691 """ 2692 Transpose the 11x to the left side of the equals sign by subtracting 2693 11x from the SymbolicEquation: 2694 """ 2695 d = c - 11*x 2696 d 2697 | 2698 5*x - 13 == 7

2699 """ 2700 Transpose the -13 to the right side of the equals sign by adding 13 2701 to the SymbolicEquation: 2702 """ 2703 e = d + 13 2704 e v1.23 - 02/17/08 SAGE For Newbies 105/150

2705 | 2706 5*x == 20

2707 """ 2708 Finally, dividing the SymbolicEquation by 5 will leave x by itself on 2709 the left side of the equals sign and produce the solution: 2710 """ 2711 f = e / 5 2712 f 2713 | 2714 x == 4

2715 """ 2716 This problem could have also be solved automatically using the 2717 solve() function: 2718 """ 2719 solve(a,x) 2720 | 2721 [x == 4]

9.1.2 Exponential Functions Wikipedia entry. http://en.wikipedia.org/wiki/Exponential_function 2722 (In development...)

9.1.3 Exponents Wikipedia entry. http://en.wikipedia.org/wiki/Exponent 2723 (In development...)

9.1.4 Expressions Wikipedia entry. http://en.wikipedia.org/wiki/Expression_(mathematics) 2724 (In development...)

9.1.5 Inequalities Wikipedia entry. http://en.wikipedia.org/wiki/Inequality 2725 (In development...)

9.1.6 Inverse Functions v1.23 - 02/17/08 SAGE For Newbies 106/150

Wikipedia entry. http://en.wikipedia.org/wiki/Inverse_function 2726 (In development...)

9.1.7 Linear Equations And Functions Wikipedia entry. http://en.wikipedia.org/wiki/Linear_functions 2727 (In development...)

9.1.8 Linear Programming Wikipedia entry. http://en.wikipedia.org/wiki/Linear_programming 2728 (In development...)

9.1.9 Logarithmic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Logarithmic_function 2729 (In development...)

9.1.10 Logistic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Logistic_function 2730 (In development...)

9.1.11 Matrices Wikipedia entry. http://en.wikipedia.org/wiki/Matrix_(mathematics) 2731 (In development...)

9.1.12 Parametric Equations Wikipedia entry. http://en.wikipedia.org/wiki/Parametric_equation 2732 (In development...)

9.1.13 Piecewise Functions Wikipedia entry. http://en.wikipedia.org/wiki/Piecewise_function 2733 (In development...)

9.1.14 Polynomial Functions Wikipedia entry. http://en.wikipedia.org/wiki/Polynomial_function 2734 (In development...) v1.23 - 02/17/08 SAGE For Newbies 107/150

9.1.15 Power Functions Wikipedia entry. http://en.wikipedia.org/wiki/Power_function 2735 (In development...)

9.1.16 Quadratic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Quadratic_function 2736 (In development...)

9.1.17 Radical Functions Wikipedia entry. http://en.wikipedia.org/wiki/Nth_root 2737 (In development...)

9.1.18 Rational Functions Wikipedia entry. http://en.wikipedia.org/wiki/Rational_function 2738 (In development...)

9.1.19 Sequences Wikipedia entry. http://en.wikipedia.org/wiki/Sequence 2739 (In development...)

9.1.20 Series Wikipedia entry. http://en.wikipedia.org/wiki/Series_mathematics 2740 (In development...)

9.1.21 Systems of Equations Wikipedia entry. http://en.wikipedia.org/wiki/System_of_equations 2741 (In development...)

9.1.22 Transformations Wikipedia entry. http://en.wikipedia.org/wiki/Transformation_(geometry) 2742 (In development...)

9.1.23 Trigonometric Functions v1.23 - 02/17/08 SAGE For Newbies 108/150

Wikipedia entry. http://en.wikipedia.org/wiki/Trigonometric_function 2743 (In development...)

2744 9.2 Precalculus And Trigonometry Wikipedia entry. http://en.wikipedia.org/wiki/Precalculus http://en.wikipedia.org/wiki/Trigonometry 2745 (In development...)

9.2.1 Binomial Theorem Wikipedia entry. http://en.wikipedia.org/wiki/Binomial_theorem 2746 (In development...)

9.2.2 Complex Numbers Wikipedia entry. http://en.wikipedia.org/wiki/Complex_numbers 2747 (In development...)

9.2.3 Composite Functions Wikipedia entry. http://en.wikipedia.org/wiki/Composite_function 2748 (In development...)

9.2.4 Conics Wikipedia entry. http://en.wikipedia.org/wiki/Conics 2749 (In development...)

9.2.5 Data Analysis Wikipedia entry. http://en.wikipedia.org/wiki/Data_analysis 2750 (In development...)

10 Discrete Mathematics: Elementary Number And Graph Theory Wikipedia entry. http://en.wikipedia.org/wiki/Discrete_mathematics 2751 (In development...)

10.1.1 Equations v1.23 - 02/17/08 SAGE For Newbies 109/150

Wikipedia entry. http://en.wikipedia.org/wiki/Equation 2752 (In development...)

10.1.2 Exponential Functions Wikipedia entry. http://en.wikipedia.org/wiki/Equation 2753 (In development...)

10.1.3 Inverse Functions Wikipedia entry. http://en.wikipedia.org/wiki/Inverse_function 2754 (In development...)

10.1.4 Logarithmic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Logarithmic_function 2755 (In development...)

10.1.5 Logistic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Logistic_function 2756 (In development...)

10.1.6 Matrices And Matrix Algebra Wikipedia entry. http://en.wikipedia.org/wiki/Matrix_(mathematics) 2757 (In development...)

10.1.7 Mathematical Analysis Wikipedia entry. http://en.wikipedia.org/wiki/Mathematical_analysis 2758 (In development...)

10.1.8 Parametric Equations Wikipedia entry. http://en.wikipedia.org/wiki/Parametric_equation 2759 (In development...)

10.1.9 Piecewise Functions Wikipedia entry. http://en.wikipedia.org/wiki/Piecewise_function 2760 (In development...) v1.23 - 02/17/08 SAGE For Newbies 110/150

10.1.10 Polar Equations Wikipedia entry. http://en.wikipedia.org/wiki/Polar_equation 2761 (In development...)

10.1.11 Polynomial Functions Wikipedia entry. http://en.wikipedia.org/wiki/Polynomial_function 2762 (In development...)

10.1.12 Power Functions Wikipedia entry. http://en.wikipedia.org/wiki/Power_function 2763 (In development...)

10.1.13 Quadratic Functions Wikipedia entry. http://en.wikipedia.org/wiki/Quadratic_function 2764 (In development...)

10.1.14 Radical Functions Wikipedia entry. http://en.wikipedia.org/wiki/Nth_root 2765 (In development...)

10.1.15 Rational Functions Wikipedia entry. http://en.wikipedia.org/wiki/Rational_function 2766 (In development...)

10.1.16 Real Numbers Wikipedia entry. http://en.wikipedia.org/wiki/Real_number 2767 (In development...)

10.1.17 Sequences Wikipedia entry. http://en.wikipedia.org/wiki/Sequence 2768 (In development...)

10.1.18 Series v1.23 - 02/17/08 SAGE For Newbies 111/150

Wikipedia entry. http://en.wikipedia.org/wiki/Series_(mathematics) 2769 (In development...)

10.1.19 Sets Wikipedia entry. http://en.wikipedia.org/wiki/Set 2770 (In development...)

10.1.20 Systems of Equations Wikipedia entry. http://en.wikipedia.org/wiki/System_of_equations 2771 (In development...)

10.1.21 Transformations Wikipedia entry. http://en.wikipedia.org/wiki/Transformation_(geometry) 2772 (In development...)

10.1.22 Trigonometric Functions Wikipedia entry. http://en.wikipedia.org/wiki/Trigonometric_function 2773 (In development...)

10.1.23 Vectors Wikipedia entry. http://en.wikipedia.org/wiki/Vector 2774 (In development...)

2775 10.2 Calculus Wikipedia entry. http://en.wikipedia.org/wiki/Calculus 2776 (In development...)

10.2.1 Derivatives Wikipedia entry. http://en.wikipedia.org/wiki/Derivative 2777 (In development...)

10.2.2 Integrals Wikipedia entry. http://en.wikipedia.org/wiki/Integral 2778 (In development...) v1.23 - 02/17/08 SAGE For Newbies 112/150

10.2.3 Limits Wikipedia entry. http://en.wikipedia.org/wiki/Limit_(mathematics) 2779 (In development...)

10.2.4 Polynomial Approximations And Series Wikipedia entry. http://en.wikipedia.org/wiki/Convergent_series 2780 (In development...)

2781 10.3 Statistics Wikipedia entry. http://en.wikipedia.org/wiki/Statistics 2782 (In development...)

10.3.1 Data Analysis Wikipedia entry. http://en.wikipedia.org/wiki/Data_analysis 2783 (In development...)

10.3.2 Inferential Statistics Wikipedia entry. http://en.wikipedia.org/wiki/Inferential_statistics 2784 (In development...)

10.3.3 Normal Distributions Wikipedia entry. http://en.wikipedia.org/wiki/Normal_distribution 2785 (In development...)

10.3.4 One Variable Analysis Wikipedia entry. http://en.wikipedia.org/wiki/Univariate 2786 (In development...)

10.3.5 Probability And Simulation Wikipedia entry. http://en.wikipedia.org/wiki/Probability 2787 (In development...)

10.3.6 Two Variable Analysis v1.23 - 02/17/08 SAGE For Newbies 113/150

Wikipedia entry. http://en.wikipedia.org/wiki/Multivariate 2788 (In development...) v1.23 - 02/17/08 SAGE For Newbies 114/150

2789 11 High School Science Problems 2790 (In development...)

2791 11.1 Physics Wikipedia entry. http://en.wikipedia.org/wiki/Physics 2792 (In development...)

11.1.1 Atomic Physics Wikipedia entry. http://en.wikipedia.org/wiki/Atomic_physics 2793 (In development...)

11.1.2 Circular Motion Wikipedia entry. http://en.wikipedia.org/wiki/Circular_motion 2794 (In development...)

11.1.3 Dynamics Wikipedia entry. http://en.wikipedia.org/wiki/Dynamics_(physics) 2795 (In development...)

11.1.4 Electricity And Magnetism Wikipedia entry. http://en.wikipedia.org/wiki/Electricity http://en.wikipedia.org/wiki/Magnetism 2796 (In development...)

11.1.5 Fluids Wikipedia entry. http://en.wikipedia.org/wiki/Fluids 2797 (In development...)

11.1.6 Kinematics Wikipedia entry. http://en.wikipedia.org/wiki/Kinematics 2798 (In development...) v1.23 - 02/17/08 SAGE For Newbies 115/150

11.1.7 Light Wikipedia entry. http://en.wikipedia.org/wiki/Light 2799 (In development...)

11.1.8 Optics Wikipedia entry. http://en.wikipedia.org/wiki/Optics 2800 (In development...)

11.1.9 Relativity Wikipedia entry. http://en.wikipedia.org/wiki/Relativity 2801 (In development...)

11.1.10 Rotational Motion Wikipedia entry. http://en.wikipedia.org/wiki/Rotational_motion 2802 (In development...)

11.1.11 Sound Wikipedia entry. http://en.wikipedia.org/wiki/Sound 2803 (In development...)

11.1.12 Waves Wikipedia entry. http://en.wikipedia.org/wiki/Waves 2804 (In development...)

11.1.13 Thermodynamics Wikipedia entry. http://en.wikipedia.org/wiki/Thermodynamics 2805 (In development...)

11.1.14 Work Wikipedia entry. http://en.wikipedia.org/wiki/Mechanical_work 2806 (In development...)

11.1.15 Energy v1.23 - 02/17/08 SAGE For Newbies 116/150

Wikipedia entry. http://en.wikipedia.org/wiki/Energy 2807 (In development...)

11.1.16 Momentum Wikipedia entry. http://en.wikipedia.org/wiki/Momentum 2808 (In development...)

11.1.17 Boiling Wikipedia entry. http://en.wikipedia.org/wiki/Boiling 2809 (In development...)

11.1.18 Buoyancy Wikipedia entry. http://en.wikipedia.org/wiki/Bouyancy 2810 (In development...)

11.1.19 Convection Wikipedia entry. http://en.wikipedia.org/wiki/Convection 2811 (In development...)

11.1.20 Density Wikipedia entry. http://en.wikipedia.org/wiki/Density 2812 (In development...)

11.1.21 Diffusion Wikipedia entry. http://en.wikipedia.org/wiki/Diffusion 2813 (In development...)

11.1.22 Freezing Wikipedia entry. http://en.wikipedia.org/wiki/Freezing 2814 (In development...)

11.1.23 Friction Wikipedia entry. http://en.wikipedia.org/wiki/Friction 2815 (In development...) v1.23 - 02/17/08 SAGE For Newbies 117/150

11.1.24 Heat Transfer Wikipedia entry. http://en.wikipedia.org/wiki/Heat_transfer 2816 (In development...)

11.1.25 Insulation Wikipedia entry. http://en.wikipedia.org/wiki/Insulation 2817 (In development...)

11.1.26 Newton's Laws Wikipedia entry. http://en.wikipedia.org/wiki/Newtons_laws 2818 (In development...)

11.1.27 Pressure Wikipedia entry. http://en.wikipedia.org/wiki/Pressure 2819 (In development...)

11.1.28 Pulleys Wikipedia entry. http://en.wikipedia.org/wiki/Pulley 2820 (In development...) v1.23 - 02/17/08 SAGE For Newbies 118/150

2821 12 Fundamentals Of Computation

2822 12.1 What Is A Computer?

2823 Many people think computers are difficult to understand because they are 2824 complex. Computers are indeed complex, but this is not why they are difficult to 2825 understand. Computers are difficult to understand because only a small part of a 2826 computer exists in the physical world. The physical part of a computer is the 2827 only part a human can see and the rest of a computer exists in a nonphysical 2828 world which is invisible. This invisible world is the world of ideas and most of a 2829 computer exists as ideas in this nonphysical world.

2830 The key to understanding computers is to understand that the purpose of these 2831 idea-based machines is to automatically manipulate ideas of all types. The name 2832 'computer' is not very helpful for describing what computers really are and 2833 perhaps a better name for them would be Idea Manipulation Devices or IMDs.

2834 Since ideas are nonphysical objects, they cannot be brought into the physical 2835 world and neither can physical objects be brought into the world of ideas. Since 2836 these two worlds are separate from each other, the only way that physical objects 2837 can manipulate objects in the world of ideas is through remote control via 2838 symbols.

2839 12.2 What Is A Symbol? 2840 A symbol is an object that is used to represent another object. Drawing 12.1 2841 shows an example of a symbol of a telephone which is used to represent a 2842 physical telephone.

Drawing 12.1: Symbol associated with a physical object. v1.23 - 02/17/08 SAGE For Newbies 119/150

2843 The symbol of a telephone shown in Drawing 12.1 is usually created with ink 2844 printed on a flat surface ( like a piece of paper ). In general, though, any type of 2845 physical matter ( or property of physical matter ) that is arranged into a pattern 2846 can be used as a symbol.

2847 12.3 Computers Use Bit Patterns As Symbols 2848 Symbols which are made of physical matter can represent all types of physical 2849 objects, but they can also be used to represent nonphysical objects in the world 2850 of ideas. ( see Drawing 12.2 )

Physical world symbols Nonphysical world of ideas

Pi

5

+

Drawing 12.2: Physical symbols can represent nonphysical ideas.

2851 Among the simplest symbols that can be formed out of physical matter are bits 2852 and patterns of bits. A single bit can only be placed into two states which are the 2853 on state and the off state. When written, typed, or drawn, a bit in the on state is 2854 represented by the numeral 1 and when it is in the off state it is represented by 2855 the numeral 0. Patterns of bits look like the following when they are written, 2856 typed, or drawn: 101, 100101101, 0101001100101, 10010.

2857 Drawing 12.3 shows how bit patterns can be used just as easily as any other 2858 symbols made of physical matter to represent nonphysical ideas. v1.23 - 02/17/08 SAGE For Newbies 120/150

Physical world symbols Nonphysical world of ideas

10100101

101

00101100

11100101001010

10100101010

Drawing 12.3: Bits can also represent nonphysical ideas.

2859 Other methods for forming physical matter into bits and bit patterns include: 2860 varying the tone of an audio signal between two frequencies, turning a light on 2861 and off, placing or removing a magnetic field on the surface of an object, and 2862 changing the voltage level between two levels in an electronic device. Most 2863 computers use the last method to hold bit patterns that represent ideas.

2864 A computer's internal memory consists of numerous "boxes" called memory 2865 locations and each memory location contains a bit pattern that can be 2866 used to represent an idea. Most computers contain millions of memory 2867 locations which allow them to easily reference millions of ideas at the same time. 2868 Larger computers contain billions of memory locations. For example, a typical 2869 purchased in 2007 contains over 1 billion memory locations.

2870 Drawing 12.4 shows a section of the internal memory of a small computer along 2871 with the bit patterns that this memory contains. v1.23 - 02/17/08 SAGE For Newbies 121/150

0 1 0 0 0 1 1 1 0 1 0 1 0 0 1 0 0 1 0 0 1 1 1 1 A computer's internal 0 0 1 0 1 1 1 0 memory is placed Each memory into “boxes” called 0 1 0 0 1 0 0 0 location in a memory locations. 0 1 0 1 0 1 0 0 computer Most computers contains a contain millions 0 1 0 0 0 0 0 1 bit pattern. of memory locations. 0 1 0 0 1 1 0 1 0 1 0 0 0 1 0 1 0 1 0 0 0 1 1 1 0 1 0 0 0 0 0 1 0 1 0 1 0 0 1 1 Drawing 12.4: Computer memory locations contain bit patterns.

2872 Each of the millions of bit pattern symbols in a computer's internal memory are 2873 capable of representing any idea a human can think of. The large number of bit 2874 patterns that most computers contain, however, would be difficult to keep track 2875 of without the use of some kind of organizing system.

2876 The system that computers use to keep track of the many bit patterns they 2877 contain consists of giving each memory location a unique address as shown in 2878 Drawing 12.5. v1.23 - 02/17/08 SAGE For Newbies 122/150

0 1 0 0 0 1 1 1 11 0 1 0 1 0 0 1 0 10 0 1 0 0 1 1 1 1 9 0 0 1 0 1 1 1 0 8 0 1 0 0 1 0 0 0 7 0 1 0 1 0 1 0 0 6 0 1 0 0 0 0 0 1 5 Each memory location is given 0 1 0 0 1 1 0 1 4 a unique address 3 so the computer 0 1 0 0 0 1 0 1 can locate it. 0 1 0 0 0 1 1 1 2 0 1 0 0 0 0 0 1 1 0 1 0 1 0 0 1 1 0 Drawing 12.5: Each memory location is given a unique address.

2879 12.4 Contextual Meaning 2880 At this point you may be wondering "how one can determine what the bit 2881 patterns in a memory location, or a set of memory locations, mean?" The answer 2882 to this question is that a concept called contextual meaning gives bit patterns 2883 their meaning.

2884 Context is the circumstances within which an event happens or the environment 2885 within which something is placed. Contextual meaning, therefore, is the 2886 meaning that a context gives to the events or things that are placed within it.

2887 Most people use contextual meaning every day, but they are not aware of it. 2888 Contextual meaning is a very powerful concept and it is what enables a 2889 computer's memory locations to reference any idea that a human can think of. 2890 Each memory location can hold a bit pattern, but a human can have that bit 2891 pattern mean anything they wish. If more bits are needed to hold a given 2892 pattern than are present in a single memory location, the pattern can be spread 2893 across more than one location.

2894 12.5 Variables 2895 Computers are very good at remembering numbers and this allows them to keep 2896 track of numerous addresses with ease. Humans, however, are not nearly as v1.23 - 02/17/08 SAGE For Newbies 123/150

2897 good at remembering numbers as computers are and so a concept called a 2898 variable was invented to solve this problem.

2899 A variable is a name that can be associated with a memory address so that 2900 humans can refer to bit pattern symbols in memory using a name instead of a 2901 number. Drawing 12.6 shows four variables that have been associated with 4 2902 memory addresses inside of a computer.

0 1 0 0 0 1 1 1 11 Variables 0 1 0 1 0 0 1 0 10 0 1 0 0 1 1 1 1 9 y 0 0 1 0 1 1 1 0 8 0 1 0 0 1 0 0 0 7 x 0 1 0 1 0 1 0 0 6 0 1 0 0 0 0 0 1 5 garage_length 0 1 0 0 1 1 0 1 4 0 1 0 0 0 1 0 1 3 garage_width 0 1 0 0 0 1 1 1 2 0 1 0 0 0 0 0 1 1 0 1 0 1 0 0 1 1 0 Drawing 12.6: Using variables instead of memory addresses.

2903 The variable names garage_width and garage_length are referencing memory 2904 locations that hold patterns that represent the dimensions of a garage and the 2905 variable names x and y are referencing memory locations that might represent 2906 numbers in an equation. Even though this description of the above variables is 2907 accurate, it is fairly tedious to use and therefore most of the time people just say 2908 or write something like “the variable garage_length holds the length of the 2909 garage.”

2910 A variable is used to symbolically represent an attribute of an object. Even 2911 though a typical personal computer is capable of holding millions of variables, 2912 most objects possess a greater number of attributes than the capacity of most 2913 computers can hold. For example, a 1 kilogram rock contains approximately 2914 10,000,000,000,000,000,000,000,000 atoms. 1 Representing even just the 2915 positions of this rock's atoms is currently well beyond the capacity of even the 2916 most advanced computer. Therefore, computers usually work with models of

1 "The Is Near" Ray Kurzweil, Viking. v1.23 - 02/17/08 SAGE For Newbies 124/150

2917 objects instead of complete representations of them.

2918 12.6 Models 2919 A model is a simplified representation of an object that only references some of 2920 its attributes. Examples of typical object attributes include weight, height, 2921 strength, and color. The attributes that are selected for modeling are chosen for 2922 a given purpose. The more attributes that are represented in the model, the 2923 more expensive the model is to make. Therefore, only those attributes that are 2924 absolutely needed to achieve a given purpose are usually represented in a model. 2925 The process of selecting only some of an object's attributes when developing a 2926 model of it is called abstraction.

2927 The following is an example which illustrates the process of problem solving 2928 using models. Suppose we wanted to build a garage that could hold 2 cars along 2929 with a workbench, a set of storage shelves, and a riding lawn mower. Assuming 2930 that the garage will have an adequate ceiling height, and that we do not want to 2931 build the garage any larger than it needs to be for our stated purpose, how could 2932 an adequate length and width be determined for the garage?

2933 One strategy for determining the size of the garage is to build perhaps 10 2934 garages of various sizes in a large field. When the garages are finished, take 2 2935 cars to the field along with a workbench, a set of storage shelves, and a riding 2936 lawn mower. Then, place these items into each garage in turn to see which is the 2937 smallest one that these items will fit into without being too cramped.

2938 The test garages in the field can then be discarded and a garage which is the 2939 same size as the one that was chosen could be built at the desired location. 2940 Unfortunately, 11 garages would need to be built using this strategy instead of 2941 just one and this would be very expensive and inefficient.

2942 A way to solve this problem less expensively is by using a model of the garage 2943 and models of the items that will be placed inside it. Since we only want to 2944 determine the dimensions of the garage's floor, we can make a scaled down 2945 model of just its floor using a piece of paper.

2946 Each of the items that will be placed into the garage could also be represented 2947 by scaled-down pieces of paper. Then, the pieces of paper that represent the 2948 items can be placed on top of the the large piece of paper that represents the 2949 floor and these smaller pieces of paper can be moved around to see how they fit. 2950 If the items are too cramped, a larger piece of paper can be cut to represent the 2951 floor and, if the items have too much room, a smaller piece of paper for the floor 2952 can be cut.

2953 When a good fit is found, the length and width of the piece of paper that 2954 represents the floor can be measured and then these measurements can be v1.23 - 02/17/08 SAGE For Newbies 125/150

2955 scaled up to the units used for the full-size garage. With this method, only a few 2956 pieces of paper are needed to solve the problem instead of 10 full-size garages 2957 that will later be discarded.

2958 The only attributes of the full-sized objects that were copied to the pieces of 2959 paper were the object's length and width. As this example shows, paper models 2960 are significantly easier to work with than the objects they represent. However, 2961 computer variables are even easier to use for modeling than paper or 2962 almost any other kind of modeling mechanism.

2963 At this point, though, the paper-based modeling technique has one important 2964 advantage over the computer variables we have look at. The paper model was 2965 able to be changed by moving the item models around and changing the size of 2966 the paper garage floor. The variables we have discussed so have been given the 2967 ability to represent an object attribute, but no mechanism has been given yet 2968 that would allow the variable's to change. A computer without the ability to 2969 change the contents of its variables would be practically useless.

2970 12.7 Machine Language 2971 Earlier is was stated that bit patterns in a computer's memory locations can be 2972 used to represent any ideas that a human can think of. If memory locations can 2973 represent any idea, this means that they can reference ideas that represent 2974 instructions which tell a computer how to automatically manipulate the 2975 variables in its memory.

2976 The part of a computer that follows the instructions that are in its memory is 2977 called a Central Processing Unit ( CPU ) or a microprocessor. When a 2978 microprocessor is following instructions in its memory, it is also said to be 2979 running them or executing them.

2980 Microprocessors are categorized into families and each microprocessor family 2981 has its own set of instructions ( called an instruction set ) that is different than 2982 the instructions that other microprocessor family's use. A microprocessor's 2983 instruction set represents the building blocks of a language that can be used to 2984 tell it what to do. This language is formed by placing sequences of 2985 instructions from the instruction set into memory and it the only language 2986 that a microprocessor is able to understand. Since this is the only language a 2987 microprocessor is able to understand, it is called machine language. A 2988 sequence of machine language instructions is called a computer program and a 2989 person who creates sequences of machine language instructions in order to tell 2990 the computer what to do is called a programmer.

2991 We will now look at what the instruction set of a simple microprocessor looks like 2992 along with a simple program which has been developed using this instruction 2993 set. v1.23 - 02/17/08 SAGE For Newbies 126/150

2994 Here is the instruction set for the 6500 family of microprocessors:

2995 ADC ADd memory to accumulator with Carry. 2996 AND AND memory with accumulator. 2997 ASL Arithmetic Shift Left one bit. 2998 BCC Branch on Carry Clear. 2999 BCS Branch on Carry Set. 3000 BEQ Branch on result EQual to zero. 3001 BIT test BITs in accumulator with memory. 3002 BMI Branch on result MInus. 3003 BNE Branch on result Not Equal to zero. 3004 BPL Branch on result PLus). 3005 BRK force Break. 3006 BVC Branch on oVerflow flag Clear. 3007 BVS Branch on oVerflow flag Set. 3008 CLC CLear Carry flag. 3009 CLD CLear Decimal mode. 3010 CLI CLear Interrupt disable flag. 3011 CLV CLear oVerflow flag. 3012 CMP CoMPare memory and accumulator. 3013 CPX ComPare memory and index X. 3014 CPY ComPare memory and index Y. 3015 DEC DECrement memory by one. 3016 DEX DEcrement register S by one. 3017 DEY DEcrement register Y by one. 3018 EOR Exclusive OR memory with accumulator. 3019 INC INCrement memory by one. 3020 INX INcrement register X by one. 3021 INY INcrement register Y by one. 3022 JMP JuMP to new memory location. 3023 JSR Jump to SubRoutine. 3024 LDA LoaD Accumulator from memory. 3025 LDX LoaD X register from memory. 3026 LDY LoaD Y register from memory. 3027 LSR Logical Shift Right one bit. 3028 NOP No OPeration. 3029 ORA OR memory with Accumulator. 3030 PHA PusH Accumulator on stack. 3031 PHP PusH Processor status on stack. 3032 PLA PuLl Accumulator from stack. 3033 PLP PuLl Processor status from stack. 3034 ROL ROtate Left one bit. 3035 ROR ROtate Right one bit. 3036 RTI ReTurn from Interrupt. 3037 RTS ReTurn from Subroutine. 3038 SBC SuBtract with Carry. v1.23 - 02/17/08 SAGE For Newbies 127/150

3039 SEC SEt Carry flag. 3040 SED SEt Decimal mode. 3041 SEI SEt Interrupt disable flag. 3042 STA STore Accumulator in memory. 3043 STX STore Register X in memory. 3044 STY STore Register Y in memory. 3045 TAX Transfer Accumulator to register X. 3046 TAY Transfer Accumulator to register Y. 3047 TSX Transfer Stack pointer to register X. 3048 TXA Transfer register X to Accumulator. 3049 TXS Transfer register X to Stack pointer. 3050 TYA Transfer register Y to Accumulator.

3051 The following is a small program which has been written using the 6500 family's 3052 instruction set. The purpose of the program is to calculate the sum of the 10 3053 numbers which have been placed into memory started at address 0200 3054 hexadecimal.

3055 Here are the 10 numbers in memory ( which are printed in blue ) along with the 3056 memory location that the sum will be stored into ( which is printed in red ). 0200 3057 here is the address in memory of the first number.

3058 0200 01 02 03 04 05 06 07 08 - 09 0A 00 00 00 00 00 3059 00 ...... 3060 3061 Here is a program that will calculate the sum of these 10 numbers:

3062 0250 A2 00 LDX #00h 3063 0252 A9 00 LDA #00h 3064 0254 18 CLC 3065 0255 7D 00 02 ADC 0200h,X 3066 0258 E8 INX 3067 0259 E0 0A CPX #0Ah 3068 025B D0 F8 BNE 0255h 3069 025D 8D 0A 02 STA 020Ah 3070 0260 00 BRK 3071 ...

3072 After the program was executed, the sum it calculated was stored in memory. 3073 The sum was determined to be 37 hex ( which is 55 decimal ) and it is shown 3074 here printed in red:

3075 0200 01 02 03 04 05 06 07 08 - 09 0A 37 00 00 00 00 00 ...... 3076 7.....

3077 Of course, you are not expected to understand how this assembly language 3078 program works. The purpose for showing it to you is so you can see what a v1.23 - 02/17/08 SAGE For Newbies 128/150

3079 program that uses a microprocessor's instruction set looks like.

3080 Low Level Languages And High Level Languages 3081 Even though programmers are able to program a computer using the 3082 instructions in its instruction set, this is a tedious task. The early computer 3083 programmers wanted to develop programs in a language that was more like a 3084 natural language, English for example, than the machine language that 3085 microprocessors understand. Machine language is considered to be a low level 3086 languages because it was designed to be simple so that it could be easily 3087 executed by the circuits in a microprocessor.

3088 Programmers then figured out ways to use low level languages to create the 3089 high level languages that they wanted to program in. This is when languages 3090 like ( in 1957 ), ALGOL ( in 1958 ), LISP ( in 1959 ), COBOL ( in 3091 1960 ), BASIC ( in 1964 ) and C ( 1972 ) were created. Ultimately, a 3092 microprocessor is only capable of understanding machine language and 3093 therefore all programs that are written in a high level language must be 3094 converted into machine language before they can be executed by a 3095 microprocessor.

3096 The rules that indicate how to properly type in code for a given programming 3097 language are called syntax rules. If a programmer does not follow the 3098 language's syntax rules when typing in a program, the software that transforms 3099 the source code into machine language will become confused and then issue 3100 what is called a syntax error.

3101 As an example of what a syntax error might look like, consider the word 'print'. 3102 If the word 'print' was a command in a given program language, and the 3103 programmer typed 'pvint' instead of 'print', this would be a syntax error.

3104 12.8 Compilers And Interpreters 3105 There are two types of programs that are commonly used to convert a higher 3106 level language into machine language. The first kind of program is called a 3107 compiler and it takes a high-level language's source code ( which is usually in 3108 typed form ) as its input and converts it into machine language. After the 3109 machine language equivalent of the source code has been generated, it can be 3110 loaded into a computer's memory and executed. The compiled version of a 3111 program can also be saved on a storage device and loaded into a computer's 3112 memory whenever it is needed.

3113 The second type of program that is commonly used to convert a high-level 3114 language into machine language is called an interpreter. Instead of converting 3115 source code into machine language like a compiler does, an interpreter reads the 3116 source code ( usually one line at a time ), determines what actions this line of 3117 source code is suppose to accomplish, and then it performs these actions. It then v1.23 - 02/17/08 SAGE For Newbies 129/150

3118 looks at the next line of source code underneath the one it just finished 3119 interpreting, it determines what actions this next line of code wants done, it 3120 performs these actions, and so on.

3121 Thousands of computer languages have been created since the 1940's, but there 3122 are currently around 2 to 3 hundred historically important languages. Here is a 3123 link to a website that lists a number of the historically important computer 3124 languages: http://en.wikipedia.org/wiki/Timeline_of_programming_languages

3125 12.9 Algorithms 3126 A computer programmer certainly needs to know at least one programming 3127 language, but when a programmer solves a problem, they do it at a level that is 3128 higher in abstraction than even the more abstract computer languages.

3129 After the problem is solved, then the solution is encoded into a programming 3130 language. It is almost as if a programmer is actually two people. The first 3131 person is the problem solver and the second person is the coder.

3132 For simpler problems, many programmers create algorithms in their minds and 3133 encode these algorithm directly into a programming language. They switch back 3134 and forth between being the problem solver and the coder during this process.

3135 With more complex programs, however, the problem solving phase and the 3136 coding phase are more distinct. The algorithm which solves a given problem is is 3137 developed using means other than a programming language and then it is 3138 recored in a document. This document is then passed from the problem solver 3139 to the coder for encoding into a programming language.

3140 The first thing that a problem solver will do with a problem is to analyze it. This 3141 is an extremely important step because if a problem is not analyzed, then it can 3142 not be properly solved. To analyze something means to break it down into its 3143 component parts and then these parts are studied to determine how they work. 3144 A well known saying is 'divide and conquer' and when a difficult problem is 3145 analyzed, it is broken down into smaller problems which are each simpler to 3146 solve than the overall problem. The problem solver then develops an 3147 algorithm to solve each of the simpler problems and, when these algorithms are 3148 combined, they form the solution to the overall problem.

3149 An algorithm ( pronounced al-gor-rhythm ) is a sequence of instructions which 3150 describe how to accomplish a given task. These instructions can be expressed in 3151 various ways including writing them in natural languages ( like English ), 3152 drawing diagrams of them, and encoding them in a programming language.

3153 The concept of an algorithm came from the various procedures that 3154 mathematicians developed for solving mathematical problems, like calculating v1.23 - 02/17/08 SAGE For Newbies 130/150

3155 the sum of 2 numbers or calculating their product.

3156 Algorithms can also be used to solve more general problems. For example, the 3157 following algorithm could have been followed by a person who wanted to solve 3158 the garage sizing problem using paper models:

3159 1) Measure the length and width of each item that will be placed into the garage 3160 using metric units and record these measurements.

3161 2) Divide the measurements from step 1 by 100 then cut out pieces of paper that 3162 match these dimensions to serve as models of the original items.

3163 3) Cut out a piece of paper which is 1.5 times as long as the model of the largest 3164 car and 3 times wider than it to serve as a model of the garage floor.

3165 4) Locate where the garage doors will be placed on the model of the garage floor, 3166 mark the locations with a pencil, and place the models of both cars on top of the 3167 model of the garage floor, just within the perimeter of the paper and between the 3168 two pencil marks.

3169 5) Place the models of the items on top of the model of the garage floor in the 3170 empty space that is not being occupied by the models of the cars.

3171 6) Move the models of the items into various positions within this empty space to 3172 determine how well all the items will fit within this size garage.

3173 7) If the fit is acceptable, go to step 10.

3174 8) If there is not enough room in the garage, increase the length dimension, the 3175 width dimension ( or both dimensions ) of the garage floor model by 10%, create 3176 a new garage floor model, and go to step 4.

3177 9) If there is too much room in the garage, decrease the length dimension, the 3178 width dimension ( or both dimensions ) of the garage model by 10%, create a 3179 new garage floor model, and go to step 4.

3180 10) Measure the length and width dimensions of the garage floor model, 3181 multiply these dimensions by 100, and then build the garage using these larger 3182 dimensions.

3183 As can be seen with this example, an algorithm often contains a significant 3184 number of steps because it needs to be detailed enough so that it leads to the 3185 desired solution. After the steps have been developed and recorded in a 3186 document, however, they can be followed over and over again by people who 3187 need to solve the given problem. v1.23 - 02/17/08 SAGE For Newbies 131/150

3188 12.10 Computation 3189 It is fairly easy to understand how a human is able to follow the steps of an 3190 algorithm, but it is more difficult to understand how computer can perform these 3191 steps when its microprocessor is only capable of executing simple machine 3192 language instructions.

3193 In order to understand how a microprocessor is able to perform the steps in an 3194 algorithm, one must first understand what computation ( which is also known 3195 as calculation ) is. Lets search for some good definitions of each of these words 3196 on the Internet and read what they have to say.”

3197 Here are two definitions for the word computation:

3198 1) The manipulation of numbers or symbols according to fixed rules. 3199 Usually applied to the operations of an automatic electronic 3200 computer, but by extension to some processes performed by minds or 3201 brains. ( www.informatics.susx.ac.uk/books/computers-and- 3202 thought/gloss/node1.html )

3203 2) A computation can be seen as a purely physical phenomenon 3204 occurring inside a closed physical system called a computer. Examples 3205 of such physical systems include digital computers, quantum 3206 computers, DNA computers, molecular computers, analog computers or 3207 wetware computers. ( www.informatics.susx.ac.uk/books/computers-and- 3208 thought/gloss/node1.html )

3209 These two definitions indicate that computation is the "manipulation of 3210 numbers or symbols according to fixed rules" and that it "can be seen as a 3211 purely physical phenomenon occurring inside a closed physical system 3212 called a computer." Both definitions indicate that the machines we normally 3213 think of as computers are just one type of computer and that other types of 3214 closed physical systems can also act as computers. These other types of 3215 computers include DNA computers, molecular computers, analog computers, and 3216 wetware computers ( or brains ).

3217 The following two definitions for calculation shed light on the kind of rules that 3218 normal computers, brains, and other types of computers use:

3219 1) A calculation is a deliberate process for transforming one or more inputs into 3220 one or more results. ( en.wikipedia.org/wiki/Calculation )

3221 2) Calculation: the procedure of calculating; determining something by mathematical 3222 or logical methods ( wordnet.princeton.edu/perl/webwn )

3223 These definitions for calculation indicate that it "is a deliberate process for 3224 transforming one or more inputs into one or more results" and that this is v1.23 - 02/17/08 SAGE For Newbies 132/150

3225 done "by mathematical or logical methods". We do not yet completely 3226 understand what mathematical and logical methods brains use to perform 3227 calculations, but rapid progress is being made in this area.

3228 The second definition for calculation uses the word logic and this word needs to 3229 be defined before we can proceed:

3230 The logic of a system is the whole structure of rules that must be 3231 used for any reasoning within that system. Most of mathematics is 3232 based upon a well-understood structure of rules and is considered to 3233 be highly logical. It is always necessary to state, or otherwise have 3234 it understood, what rules are being used before any logic can be 3235 applied. ( ddi.cs.uni-potsdam.de/Lehre/TuringLectures/MathNotions.htm 3236 )

3237 Reasoning is the process of using predefined rules to move from one point in a 3238 system to another point in the system. For example, when a person adds 2 3239 numbers together on a piece of paper, they must follow the rules of the addition 3240 algorithm in order to obtain a correct sum. The addition algorithm's rules are its 3241 logic and, when someone applies these rules during a calculation, they are 3242 reasoning with the rules.

3243 Lets now apply these concepts to the question about how a computer can 3244 perform the steps of an algorithm when its microprocessor is only capable of 3245 executing simple machine language instructions. When a person develops an 3246 algorithm, the steps in the algorithm are usually stated as high-level tasks which 3247 do not contain all of the smaller steps that are necessary to perform each task.

3248 For example, a person might write a step that states "Drive from New York to 3249 San Francisco." This large step can be broken down into smaller steps that 3250 contain instructions such as "turn left at the intersection, go west for 10 3251 kilometers, etc." If all of the smaller steps in a larger step are completed, then 3252 the larger step is completed too.

3253 A human that needs to perform this large driving step would usually be able to 3254 figure out what smaller steps need to be performed in order accomplish it. 3255 Computers are extremely stupid, however, and before any algorithm can be 3256 executed on a computer, the algorithm's steps must be broken down into smaller 3257 steps, and these smaller steps must be broken down into even small steps, until 3258 the steps are simple enough to be performed by the instruction set of a 3259 microprocessor.

3260 Sometimes only a few smaller steps are needed to implement a larger step, but 3261 sometimes hundreds or even thousands of smaller steps are required. Hundreds 3262 or thousands of smaller steps will translate into hundreds or thousands of 3263 machine language instructions when the algorithm is converted into machine v1.23 - 02/17/08 SAGE For Newbies 133/150

3264 language.

3265 If machine language was the only language that computers could be 3266 programmed in, then most algorithms would be too large to be placed into a 3267 computer by a human. An algorithm that is encoded into a high-level language, 3268 however, does not need to be broken down into as many smaller steps as would 3269 be needed with machine language. The hard work of further breaking down an 3270 algorithm that has been encoded into a high-level language is automatically done 3271 by either a compiler or an interpreter. This is why most of the time, 3272 programmers use a high-level language to develop in instead of machine 3273 language.

3274 12.11 Diagrams Can Be Used To Record Algorithms 3275 Earlier it was mentioned that not only can an algorithm can be recorded in a 3276 natural language like English but it can also be recorded using diagrams. You 3277 may be surprised to learn, however, that a whole diagram-based language has 3278 been created which allows all aspects of a program to be designed by 'problem 3279 solvers', including the algorithms that a program uses. This language is call 3280 UML which stands for Unified Modeling Language. One of UML's diagrams is 3281 called an Activity diagram and it can be used to show the sequence of steps (or 3282 activities) that are part of some piece of logic. The following is an example 3283 which shows how an algorithm can be represented in an Activity diagram.

12.12 Calculating The Sum Of The Numbers Between 1 And 10 3284 The first thing that needs to be done with a problem before it can be analyzed 3285 and solved is to describe it clearly and accurately. Here is a short description for 3286 the problem we will solve with an algorithm:

3287 Description: In this problem, the sum of the numbers between 1 and 10 3288 inclusive needs to be determined.

3289 Inclusive here means that the numbers 1 and 10 will be included in the sum. 3290 Since this is a fairly simple problem we will not need to spend too much time 3291 analyzing it. Drawing 12.7 shows an algorithm for solving this problem that has 3292 been placed into an Activity diagram. v1.23 - 02/17/08 SAGE For Newbies 134/150

Logic entry point Variable simulation Variables ( indicated by 0 sum: holds the accumulating sum. solid circle ). boxes. Place 0 into 1 count: holds the current number that is being added to sum and also variable sum. is used to determine when the summing loop should be exited.

Place 1 into Variables ( along with variable count. their descriptions ) are Arrows indicate recorded in a list as the algorithm's they are created to Rounded rectangles flow of logic. support the logic in contain algorithm the algorithm. steps/activities.

Add count to sum and place result Diamonds back into sum. are used for making decisions An arrow that points by branching to an earlier part of and for merging the diagram indicates back into the Add 1 a loop. flow of logic. to count.

[count is not equal to 11.]

Logic exit point ( indicated by Statements in brackets indicate solid circle with the conditions under which a a ring around it ). given branch out of a logic flow occurs. Drawing 12.7: Activity diagram for an algorithm.

3293 An algorithms and its Activity diagram are developed at the same time. During 3294 the development process, variables are created as needed and their names are 3295 usually recorded in a list along with their descriptions. The developer 3296 periodically starts at the entry point and walks through the logic to make sure it 3297 is correct. Simulation boxes are placed next to each variable so that they can be 3298 use to record and update how the logic is changing the variable's values. During 3299 a walk-through, errors are usually found and these need to be fixed by moving 3300 flow arrows and adjusting the text that is inside of the activity rectangles.

3301 When the point where no more errors in the logic can be found, the developer 3302 can stop being the problem solver and pass the algorithm over to the coder so 3303 it can be encoded into a programming language. v1.23 - 02/17/08 SAGE For Newbies 135/150

3304 12.13 The Mathematics Part Of Mathematics Computing 3305 Systems 3306 Mathematics has been described as the "science of patterns" 2. Here is a 3307 definition for pattern:

3308 1) Systematic arrangement... 3309 (http://www.answers.com/topic/pattern)

3310 And here is a definition for system:

3311 1) A group of interacting, interrelated, or interdependent elements 3312 forming a complex whole.

3313 2) An organized set of interrelated ideas or principles. 3314 (http://www.answers.com/topic/system)

3315 Therefore, mathematics can be though of as a science that deals with the 3316 systematic properties of physical and nonphysical objects. The reason that 3317 mathematics is so powerful is that all physical and nonphysical objects posses 3318 systematic properties and therefore, mathematics is a means by which these 3319 objects can be understood and manipulated.

3320 The more mathematics a person knows, the more control they are able to have 3321 over the physical world. This makes mathematics one of the most useful and 3322 exciting areas of knowledge a person can possess.

3323 Traditionally, learning mathematics also required learning the numerous tedious 3324 and complex algorithms that were needed to perform written calculations with 3325 mathematics. Usually over 50% of the content of the typical traditional math 3326 textbook is devoted to teaching writing-based algorithms and an even higher 3327 percentage of the time a person spends working through a textbook is spent 3328 manually working these algorithms.

3329 For most people, learning and performing tedious, complex written-calculation 3330 algorithms is so difficult and mind-numbingly boring that they never get a 3331 chance to see that the "mathematics" part of mathematics is extremely exciting, 3332 powerful, and beautiful.

3333 The bad news is that writing-based calculation algorithms will always be tedious, 3334 complex, and boring. The good news is that the invention of mathematics 3335 computing environments has significantly reduced the need for people to use 3336 writing-based calculation algorithms.

1 2 Steen, Lynn Arthur. “The Science of Patterns.” Science 240 (April 1988): 611-616. v1.23 - 02/17/08 SAGE For Newbies 136/150

3337 13 Setting Up A SAGE Server 3338 As indicated in a previous section, most people will first use SAGE as a web 3339 service and the assumption was made at the beginning of this book that the 3340 reader already had access to a SAGE server. This section is for people who want 3341 to have their own SAGE server and it covers obtaining, installing, configuring, 3342 and maintaining one on Windows or Linux.

3343 Since the SAGE Notebook Server is based on Internet technologies, this section 3344 will start by covering some of these technologies. A high-level view of SAGE's 3345 architecture will then be given followed by a discussion of the contents of the 3346 SAGE distribution files. Finally, setting up both Linux and Windows-based SAGE 3347 servers will be covered.

13.1 An Introduction To Internet-based Technologies 3348 The Internet is currently one of the most important technologies of our 3349 civilization and its importance will only increase in the future. In fact, the 3350 Internet is expanding so quickly that projections show almost all computing 3351 devices will eventually be connected to it 3352 ( https://embeddedjava.dev.java.net/resources/waves_of_the_internet_telemetry.p 3353 df ). Therefore, understanding how Internet-related technologies work is 3354 valuable for anyone who is interested in working with computers.

3355 Understanding the history of how the Internet was created is also valuable, but 3356 we will not be discussing this history here because it has been well documented 3357 elsewhere. I highly recommend that you do an Internet search on the history of 3358 the Internet and read some of the articles you find. I assure you that it will be an 3359 excellent investment of your time.

13.1.1 How do multiple computers communicate with each other? 3360 When only 2 computers need to communicate with each other, the situation is 3361 simple because all that is needed is to connect them together with a 3362 communications medium (such as copper wires, fiber optic cables, or wireless 3363 radio signals). The information that leaves one computer is sent to the other 3364 computer and vice versa. But what about the situation where multiple 3365 computers need to communication with each other? There are a number of ways 3366 to solve this problem and one of the more common ways is shown in Figure 11:

3367 Figure 11 shows multiple computers connected to what is called a Local Area 3368 Network or LAN. A LAN consists of multiple computers that are physically 3369 close to each other (usually in the same room or in the same building) and v1.23 - 02/17/08 SAGE For Newbies 137/150

3370 attached to each other using some kind of communications medium. In Drawing 3371 13.1, the computers are attached to a device called a switch with copper 3372 Ethernet cables.

Local Area Network ( LAN ) Sage Server B DHCP Server DNS Server PC #1

Copper Gateway Internet Ethernet Switch Cable

PC #2 Sage Server A Sage Server C PC #3 PC #4

Drawing 13.1: A Local Area Network (LAN)

3373 Computers on a network communicate with each other using messages and 3374 sending a message is similar to sending a letter through the mail. The purpose 3375 of a switch is to look at each message that is sent into it, determine which 3376 computer the message is being sent to, and then sending the message to that 3377 computer.

3378 There is a problem with the model in Figure 11, however, because the names 3379 that are associated with each computer on the network would not be suitable for 3380 uniquely identifying them if their numbers would be increased into the hundreds 3381 or thousands. Beyond this, the cloud on the right side of the figure represents 3382 the Internet and the millions of computers (which are also called hosts) that are 3383 currently attached to it. Messages can also be sent to these computers and 3384 received from them, but only if each computer on the Internet is uniquely 3385 identified in some way. Beyond this, rules for how the messages are to be 3386 exchanged must also exist.

13.1.2 The TCP/IP protocol suite 3387 Two problems that needed to be solved before the Internet could be created 3388 were 1) each computer needed to be uniquely identified and 2) communications 3389 rules ( also called protocols ) needed to be developed which determined how the v1.23 - 02/17/08 SAGE For Newbies 138/150

3390 messages were to be exchanged. With respect to the Internet, a protocol can be 3391 defined as "a set of rules that define an exact format for communication 3392 between systems." ( www.unitedyellowpages.com/internet/terminology.html ). 3393 When a number of protocols are used together, they are called a protocol suite.

3394 The protocol suite that was developed for the Internet is called TCP/IP and its 3395 name is a combination of the names of the two most heavily used protocols in the 3396 suite (TCP stands for Transmission Control Protocol and IP stands for 3397 Internet Protocol). The Internet Protocol defines a way to uniquely identify 3398 computers on the Internet using an addressing system. IP version 4 (IPv4), 3399 which is currently the most widely used version of the IP protocol, consists of 4 3400 numbers between 0 and 255 separated from each other by a dot. 3401 Examples of IP address include 207.21.94.50, 54.3.59.2, and 204.74.99.100. All 3402 the IPv4 addresses from 0.0.0.0 to 255.255.255.255 create an address space 3403 which contains 4,294,967,296 addresses.

3404 IP version 6 (IPv6) is the newest version of the IP protocol and it has an address 3405 space which contains 340,282,366,920,938,463,463,374,607,431,768,211,456 3406 addresses! The transition from IPv4 to IPv6 has begun, but it is moving slowly. 3407 Most hosts on the Internet will continue to use the IPv4 protocol for a long time 3408 and therefore IPv4 is what we will use in this document.

3409 Drawing 13.2 contains the same model of a network that was shown in Drawing 3410 13.1 but with IPv4 addresses assigned to each computer:

Local Area Network ( LAN ) with IPv4 addresses 147.15.50.2 207.21.94.4 207.21.94.2 Sage Server B DHCP Server DNS 207.21.94.100 Server PC #1 207.21.94.1 Copper Gateway Internet Ethernet Switch Cable

PC #2 207.21.94.182

207.21.94.127 Sage Server A Sage Server C PC #3 PC #4 98.1.200.129 207.21.94.72 207.21.94.214

Drawing 13.2: IP Addresses. v1.23 - 02/17/08 SAGE For Newbies 139/150

3411 If PC #3 needed to send a message to PC #4, the IP address of PC #4 (which is 3412 207.21.94.214) would be placed into the message. The IP address of the sender 3413 (207.21.94.72) is also placed into the message in case PC #4 needs to send a 3414 reply (this is similar to placing a return address on a letter). PC #3 will then 3415 send the message to the switch, the switch will look at the message's destination 3416 address and then pass the message to PC #4.

3417 If one of the computers on this local network needs to send a message to a 3418 computer which is not on the LAN, then the message is sent to the gateway 3419 computer and the gateway will then route the message to the Internet.

13.1.3 Clients and servers 3420 On LANs and on the Internet, there are a number of ways for communications 3421 between computers to be organized and these organizations are often called 3422 architectures. One architecture is called Peer-to-Peer (P2P) and it treats 3423 computers on the network as equals that exchange information with each other. 3424 An example of a P2P application is instant messaging.

3425 Another architecture that is used with networked computers is called Client- 3426 Server. With a Client-Server architecture, a server is a computer that accept 3427 requests from other computers on the network, performs the work that was 3428 requested, and returns the results of the work to the requester. A client is a 3429 computer that sends a request to a server, receives a response, and then makes 3430 use of the information that was contained in the response.

3431 In the LAN shown in Figure 11, there are 3 servers (a DHCP server, a DNS 3432 server, and a SAGE server) and 4 clients. The DHCP and DNS servers will be 3433 discussed in the next two sections.

13.1.4 DHCP 3434 DHCP stands for Dynamic Host Configuration Protocol and its purpose is to 3435 allow computers on a LAN to automatically be configured when they are booted 3436 up with the information they need to access the network. This information 3437 includes an IP address, the address of the gateway, and the address of a 3438 DNS server. We have already discussed what an IP address is and what a 3439 gateway is. DNS servers will be covered in the next section.

3440 What you might be wondering at this point is how a computer that doesn't have 3441 an IP address yet (because it is booting up) is able to use the network to contact 3442 the DHCP server to obtain an IP address. This problem is solved by having the 3443 booting computer send a DHCP broadcast message to the LAN. Broadcast 3444 messages are not sent to any specific machine on a LAN. Instead, broadcast 3445 messages are sent to the LAN as a whole and all the computers that are on the 3446 LAN receive the message. v1.23 - 02/17/08 SAGE For Newbies 140/150

3447 If a DHCP request message is broadcast to the LAN, the DHCP server will 3448 receive the request at the same time that the rest of the computers do. The 3449 other computers will read the contents of the message, see that it contains a 3450 DHCP request, and then they will ignore it. The DHCP server, however, will read 3451 the contents of the message, see that the message was meant for it, and send 3452 DHCP configuration information back to the sender.

13.1.5 DNS 3453 Each of the millions of computers on the Internet can be accessed using their IP 3454 addresses. For example, the IP address the server that contains the 3455 sagemath.org website is 128.208.160.192. You can access this website directly 3456 by launching a web browser and then entering http://128.208.160.192/sage in 3457 the URL bar.

3458 It is difficult for humans to remember numerous numbers, however, so a system 3459 for associating names with IP address numbers was created for the 3460 Internet. The name of the system is DNS and it stands for Domain Name 3461 System. A name that is associated with one or more IP address is called a 3462 domain name and a domain name that has a given machine's hostname at its 3463 beginning (and a period at its end) is called a fully qualified domain name. 3464 Examples of domain names are:

3465 gentoo.org 3466 yahoo.com 3467 .net 3468 google.com 3469 sagemath.org 3470 wikipedia.com

3471 Examples of fully qualified domain names are:

3472 kiwi.gentoo.org. 3473 loon.gentoo.org. 3474 wren.gentoo.org.

3475 DNS is implemented as a large database that is distributed across the whole 3476 Internet. Domain names need to be registered with a domain name registry 3477 organization before they will be entered into the DNS system. Examples of 3478 domain name registry companies include godaddy.com, networksolutions.com, 3479 and register.com.

3480 The DNS server on the LAN in Figure 12 has three functions. The first function 3481 is to accept messages that contain domain names from clients and to return the 3482 IP address that are associated with these names. When a user types in a v1.23 - 02/17/08 SAGE For Newbies 141/150

3483 domain name like sagemath.org into a browser's URL bar, the browser cannot 3484 contact the SAGE website server yet because it does not know its IP address. 3485 The operating system that the browser is running on will therefore send the 3486 domain name to the DNS server (using the DNS server's IP address that it 3487 obtained through DHCP) and the DNS server will respond with one or more IP 3488 address that are associated with the sagemath.org domain name. The system 3489 will then use one of these IP address to contact the server that the SAGE website 3490 is on.

3491 The second function that a local DNS server has is to define the domain name 3492 to IP address mappings for the machines on the local network. If a remote 3493 computer on the Internet wants to know the IP address for a machine on the 3494 local network, and its DNS server does not know the mapping, the remote DNS 3495 server will contact the local authoritative DNS server to ask what the mapping 3496 is. The remote DNS server will then remember this mapping for a certain time 3497 in case machines on the remote network need to know the mapping in the future.

3498 The third function that a DNS server has is to take messages that contain IP 3499 addresses and return the domain names that are associated with these 3500 addresses.

13.1.6 Processes and ports 3501 Now that we have discussed some of the more important technologies that are 3502 related to the Internet, it is time talk about what happens when IP messages 3503 (referred to as messages from now on) arrive at a computer and what generates 3504 messages before they are sent from a computer.

3505 Almost all modern personal computers can have multiple programs running on 3506 them concurrently. Here is a list of programs that may be running concurrently 3507 on a typical user's computer:

3508 - Web browser. 3509 - Instant message client. 3510 - Word processor. 3511 - File download utility. 3512 - Audio file player. 3513 - Computer game.

3514 In most computers operating systems running programs are called processes. 3515 In Windows, a list of all the processes that are currently running can be seen by 3516 running the Task Manager, which is launched by pressing the 3517 and keys simultaneously. On UNIX-based systems like 3518 Linux, a list of the running processes can be obtained by executing a ps -e 3519 command. Here is the list of process that were running on a Linux system which 3520 I ha v1.23 - 02/17/08 SAGE For Newbies 142/150

3521 manage@sage:~$ ps -e 3522 PID TTY TIME CMD 3523 1 ? 00:00:00 init 3524 2 ? 00:00:00 ksoftirqd/0 3525 3 ? 00:00:00 watchdog/0 3526 4 ? 00:00:00 events/0 3527 5 ? 00:00:00 khelper 3528 6 ? 00:00:00 kthread 3529 8 ? 00:00:00 kblockd/0 3530 9 ? 00:00:00 kacpid 3531 10 ? 00:00:00 kacpi_notify 3532 67 ? 00:00:00 kseriod 3533 100 ? 00:00:00 pdflush 3534 101 ? 00:00:00 pdflush 3535 102 ? 00:00:00 kswapd0 3536 103 ? 00:00:00 aio/0 3537 1545 ? 00:00:00 scsi_eh_0 3538 1547 ? 00:00:00 scsi_eh_1 3539 1728 ? 00:00:02 kjournald 3540 1796 ? 00:00:00 logd 3541 1914 ? 00:00:01 udevd 3542 2611 ? 00:00:00 shpchpd 3543 2620 ? 00:00:00 kpsmoused 3544 3208 tty2 00:00:00 getty 3545 3209 tty3 00:00:00 getty 3546 3210 tty4 00:00:00 getty 3547 3211 tty5 00:00:00 getty 3548 3212 tty6 00:00:00 getty 3549 3263 ? 00:00:00 dd 3550 3265 ? 00:00:00 klogd 3551 3345 ? 00:00:14 vmware-guestd 3552 3381 ? 00:00:00 sshd 3553 3404 ? 00:00:00 atd 3554 3414 ? 00:00:00 cron 3555 3959 ? 00:00:00 dhclient3 3556 4140 tty1 00:00:00 login 3557 4141 tty1 00:00:00 bash 3558 4429 ? 00:00:00 syslogd 3559 4507 ? 00:00:00 sshd 3560 4508 pts/1 00:00:00 bash 3561 4538 tty1 00:00:00 sage 3562 4541 tty1 00:00:00 sage-sage 3563 4554 tty1 00:00:00 python 3564 4555 tty1 00:00:05 sage- 3565 4573 tty1 00:00:00 sh 3566 4574 tty1 00:00:00 sage v1.23 - 02/17/08 SAGE For Newbies 143/150

3567 4580 tty1 00:00:00 sage-sage 3568 4591 tty1 00:00:02 python 3569 4592 pts/2 00:00:00 sage 3570 4600 pts/2 00:00:00 sage-sage 3571 4611 pts/2 00:00:06 python 3572 4611 pts/1 00:00:00 ps

3573 If you look towards the bottom of this list you can see SAGE running along with 3574 the SAGE Notebook server. Notice that the ps command included itself in the 3575 list because it was running at the moment that the list was created.

3576 There are four columns in this listing. Each process is given a unique Process 3577 ID (PID) number when the process is created and these numbers are listed in the 3578 PID column. The TTY column indicates whether or not a process is attached to 3579 a terminal and if it is, what terminal it is attached to. The TIME column 3580 indicates how much CPU time the process has used so far in hours, minutes and 3581 seconds . 3582 3583 When a message arrives at a computer from the network, the computer must 3584 decide which process to give the message to. The way that the TCP/IP protocol 3585 solves this problem is with software-based communications ports.

Communications Inside Outside ports computer computer 206.21.94.132

Port 10

Port 9 Process 2348 Communications Port 8 cable Port 7 Incoming message

Port 6 IP: 206.21.94.132 Process 2023 Port 5 Port: 5 Data Port 4

Port 3 Process 2568 Port 2

Port 1

Port 0 Drawing 13.3: Communications ports. v1.23 - 02/17/08 SAGE For Newbies 144/150

3586 Drawing 13.3 shows the inside and the outside of a computer that is connected 3587 to a network and which has an IP address of 206.21.94.132. The 3588 communications ports are placed between the processes that are running on the 3589 left and the network connection on the right. Each port is given a unique 3590 number with the lowest port number being 0 and the highest port number being 3591 65535. Each message that arrives from the network has a port number included 3592 in it so that the system knows which port to send the message to.

3593 In Drawing 13.3, a message which has port 5 as its destination port has arrived 3594 from the network and therefore the system will place this message into port 5. 3595 Process 2023 has been bound to port 5 and, when the system sends the 3596 message to this port, process 2023 will take the message and then do 3597 something with the information it contains.

3598 Drawing 13.4 shows a message from process 2023 being sent to another 3599 computer on the network which has an IP address of 65.22.8.3. When this 3600 messages arrives at the destination computer, it will place the message into it's 3601 port 8 and hopefully there is a process at that computer which is bound to port 3602 8.

Communications Inside Outside ports computer computer 206.21.94.132

Port 10

Port 9 Process 2348 Communications Port 8 cable Port 7 Outgoing message

Port 6 IP: 65.22.8.3 Process 2023 Port 5 Port: 8 Data Port 4

Port 3 Process 2568 Port 2

Port 1

Port 0 Drawing 13.4: An outgoing message. v1.23 - 02/17/08 SAGE For Newbies 145/150

13.1.7 Well known ports, registered ports, and dynamic ports 3603 Now that you know what ports are and how processes are bound to them, you 3604 may be wondering how people determine which processes should be bound to 3605 which ports. An organization called IANA (Internet Assigned Numbers 3606 Authority) is responsible for various number schemes associated with the 3607 Internet and one of them is the TCP/IP port scheme. IANA has divided the 0 - 3608 65535 port range into the following three address blocks:

3609 0 - 1023 -> Well Known Ports.

3610 1024 - 49151 -> Registered Ports.

3611 49152 - 65535 -> Dynamic and or Private Ports.

3612 13.1.7.1 Well known ports (0 - 1023) 3613 A list is maintained by IANA which indicates which kinds of programs are usually 3614 bound to specific port numbers in this range. For example, web servers are 3615 bound to port 80, SSH (secure shell) servers are bound to port 22, FTP (File 3616 Transfer Protocol servers are bound to port 20, and DNS servers are bound 3617 to port 53. Here is a list of the first 25 well known ports and the full list can be 3618 obtained at http://www.iana.org/assignments/port-numbers:

3619 Keyword Decimal Description References 3620 ------3621 0/tcp Reserved 3622 0/udp Reserved 3623 # Jon Postel 3624 tcpmux 1/tcp TCP Port Service Multiplexer 3625 tcpmux 1/udp TCP Port Service Multiplexer 3626 # Mark Lottor 3627 compressnet 2/tcp Management Utility 3628 compressnet 2/udp Management Utility 3629 compressnet 3/tcp Compression Process 3630 compressnet 3/udp Compression Process 3631 # Bernie Volz 3632 # 4/tcp Unassigned 3633 # 4/udp Unassigned 3634 rje 5/tcp Remote Job Entry 3635 rje 5/udp Remote Job Entry 3636 # Jon Postel 3637 # 6/tcp Unassigned 3638 # 6/udp Unassigned v1.23 - 02/17/08 SAGE For Newbies 146/150

3639 echo 7/tcp Echo 3640 echo 7/udp Echo 3641 # Jon Postel 3642 # 8/tcp Unassigned 3643 # 8/udp Unassigned 3644 discard 9/tcp Discard 3645 discard 9/udp Discard 3646 # Jon Postel 3647 discard 9/dccp Discard SC:DISC 3648 # IETF dccp WG, Eddie Kohler 3649 , [RFC4340] 3650 # 10/tcp Unassigned 3651 # 10/udp Unassigned 3652 11/tcp Active Users 3653 systat 11/udp Active Users 3654 # Jon Postel 3655 # 12/tcp Unassigned 3656 # 12/udp Unassigned 3657 daytime 13/tcp Daytime (RFC 867) 3658 daytime 13/udp Daytime (RFC 867) 3659 # Jon Postel 3660 # 14/tcp Unassigned 3661 # 14/udp Unassigned 3662 # 15/tcp Unassigned [was netstat] 3663 # 15/udp Unassigned 3664 # 16/tcp Unassigned 3665 # 16/udp Unassigned 3666 qotd 17/tcp Quote of the Day 3667 qotd 17/udp Quote of the Day 3668 # Jon Postel 3669 msp 18/tcp Message Send Protocol 3670 msp 18/udp Message Send Protocol 3671 # Rina Nethaniel <---none---> 3672 chargen 19/tcp Character Generator 3673 chargen 19/udp Character Generator 3674 ftp-data 20/tcp File Transfer [Default Data] 3675 ftp-data 20/udp File Transfer [Default Data] 3676 ftp 21/tcp File Transfer [Control] 3677 ftp 21/udp File Transfer [Control] 3678 # Jon Postel 3679 ssh 22/tcp SSH Remote Login Protocol 3680 ssh 22/udp SSH Remote Login Protocol 3681 # Tatu Ylonen 3682 telnet 23/tcp Telnet 3683 telnet 23/udp Telnet 3684 # Jon Postel 3685 24/tcp any private mail system v1.23 - 02/17/08 SAGE For Newbies 147/150

3686 24/udp any private mail system 3687 # Rick Adams 3688 smtp 25/tcp Simple Mail Transfer 3689 smtp 25/udp Simple Mail Transfer

3690 When one computer on the network wants to make use of a specific service that 3691 is running on another computer on the network, the first computer creates a 3692 message, places the port number of the desired service into the message, and 3693 then sends it to the destination computer. If a process that implements the well 3694 known service for that port is bound to the port, then this process will receive 3695 the message and perform the requested work.

3696 The main restriction on processes that are bound to ports in the well known 3697 ports range is that they must be running with super user privileges.

3698 13.1.7.2 Registered ports (1024 - 49151) 3699 Registered ports work similarly to well known ports except that the 3700 processes that are bound to them do not need to be running with super user 3701 privileges. The list of registered ports is included in the same IANA 3702 document that contains the list of well known ports.

3703 13.1.7.3 Dynamic/private ports (49152 - 65535) 3704 These ports are used as needed and they do not have any specific type of process 3705 associated with them. A typical use of the ports in this range is for a web 3706 browser to make an outgoing connection with a web server.

13.1.8 The SSH (Secure SHell) service 3707 An example of a service that makes itself available through a well known port is 3708 the SSH (Secure SHell) service and it is usually bound to port 22. The SSH 3709 service allows a person to log into one computer on a network from another 3710 computer on the network. The person must know the username and password 3711 for an account on the remote machine before logging into it and the remote 3712 machine must have a SSH service (in the form of a process) running and bound 3713 to port 22. SSH is able to provide a secure connection between the machines by 3714 encrypting the data that is passed between them.

3715 On UNIX-based systems, the SSH client program is simply called SSH and on 3716 Windows systems you can download and install a program called .exe that 3717 will allow you to remotely log into a machine that is running the ssh service. The 3718 putty.exe program can be downloaded from ( 3719 http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).

3720 When the ssh client program is asked to log into a remote machine for the first 3721 time, it tells the user that it does not currently have encryption information for v1.23 - 02/17/08 SAGE For Newbies 148/150

3722 this host and asks if it should continue. Answer by typing the word "yes". The 3723 program then indicates that it added information about this host to a known 3724 hosts list and it will not ask the question again in the future.

13.1.9 Using scp to copy files between machines on the network 3725 The SSH service is not only able to allow a user to log into a remote machine, it 3726 can also be used to copy files between machines on the network. The Linux 3727 client program for copying files is called scp ( Secure Copy ) and a popular 3728 Windows scp client, called pscp.exe, can be obtained from the same url that 3729 putty.exe was.

3730 13.2 SAGE's Architecture (in development) v1.23 - 02/17/08 SAGE For Newbies 149/150

Standard Python Sage notebook server Environment “Expect” Screen scraping Sage preprocessor pseudo tty (x^2 converted to x**2, etc) connection

Parts of Sage which are implemented in Python by the core Sage developers

Parts of Sage which are Parts of Sage which are implemented with implemented with pseudo tty-based math-oriented screen scraping connections python modules to various applications

scipy mathplotlib etc.

“Expect” “Expect” “Expect” Screen Screen Screen scraping scraping scraping pseudo tty pseudo tty pseudo tty connection connection connection

Maxima Gap etc.

Drawing 13.5: SAGE's architecture. v1.23 - 02/17/08 SAGE For Newbies 150/150

3731 13.3 Linux-Based SAGE Distributions 3732 (In development...)

3732 13.4 The VMware Virtual Machine Distribution Of SAGE 3733 (Mostly For Windows Users) 3734 (In development...)