www.it-ebooks.info
Sage
Beginner's Guide
Unlock the full potenal of Sage for simplifying and
automang mathemacal compung
Craig Finch
BIRMINGHAM - MUMBAI
www.it-ebooks.info
Sage
Beginner's Guide
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this informaon.
First published: May 2011
Producon Reference: 1250411
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849514-46-0
www.packtpub.com
Cover Image by Ed Maclean ()
of Central Florida (UCF). He earned a Bachelor of Science degree from the University
of Illinois at Urbana-Champaign and a Master of Science degree from UCF, both in
electrical engineering. Craig worked as a design engineer for TriQuint Semiconductor, and
currently works as a research assistant in the Hybrid Systems Lab at the UCF NanoScience
Technology Center. Craig's professional goal is to develop tools for computaonal science
and engineering and use them to solve dicult problems. In parcular, he is interested
in developing tools to help biologists study living systems. Craig is commied to using,
developing, and promong open-source soware. He provides documentaon and "how-to"
examples on his blog at .
I would like to thank my advisers, Dr. J. Hickman and Dr. Tom Clarke, for
giving me the opportunity to pursue my doctorate. I would also like to
thank my parents for buying the Apple IIGS computer that started it all.
www.it-ebooks.info
About the Reviewers
Dr. David Kirkby is a chartered engineer living in Essex, England. David has a B.Sc. in
Electrical and Electronic Engineering, an M.Sc. in Microwaves and OptoElectronics, and a
Ph.D. in Medical Physics. Despite David's Ph.D. being in Medical Physics, it was primarily an
engineering project, measuring the opcal properes of human ssue, with a mixture of
Monte Carlo modeling, radio frequency design, and laser opcs. David was awarded his Ph.D.
in 1999 from University College London.
Although not a mathemacian, Dr. Kirkby has made extensive use of mathemacal soware.
Most of his experience has been with MathemacaTM from Wolfram Research, although he
has used both MATLAB
TM
and Simulink
TM
too.
David is the author of a number of open-source projects, including soware for modeling
transmission lines using nite dierence (
design of
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at
www.PacktPub.com and as a print
book customer, you are entled to a discount on the eBook copy. Get in touch with us at
for more details.
At
www.PacktPub.com, you can also read a collecon of free technical arcles, sign up for a
range of free newsleers and receive exclusive discounts and oers on Packt books and eBooks.
Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's enre library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy & paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine enrely free books. Simply use your login credenals for
immediate access.
www.it-ebooks.info
www.it-ebooks.info
Table of Contents
Preface 1
Chapter 1: What Can You Do with Sage? 9
Geng started 9
Using Sage as a powerful calculator 12
Symbolic mathemacs 14
Linear algebra 17
Downloading and decompressing source tarball 39
Building Sage 39
Installaon 39
Summary 39
Chapter 3: Geng Started with Sage 41
How to get help with Sage 41
Starng Sage from the command line 42
Using the interacve shell 43
Time for acon – doing calculaons on the command line 43
Geng help 45
Command history 46
Tab compleon 47
Interacvely tracing execuon 48
Using the notebook interface 48
Starng the notebook interface 49
Time for acon – doing calculaons with the notebook interface 52
Geng help in the notebook interface 54
Working with cells 54
Working with code 55
Closing the notebook interface 55
Displaying results of calculaons 56
Operators and variables 56
Arithmec operators 57
Numerical types 58
Integers and raonal numbers 58
Real numbers 59
Complex numbers 60
Symbolic expressions 60
Dening variables on rings 61
Combining types in expressions 62
List funcons and methods 87
Tuples: read-only lists 87
Time for acon – returning mulple values from a funcon 87
Strings 89
Time for acon – working with strings 90
Other sequence types 92
For loops 92
Time for acon – iterang over lists 92
Time for acon – compung a soluon to the diusion equaon 94
List comprehensions 99
Time for acon – using a list comprehension 99
While loops and text le I/O 101
Time for acon – saving data in a text le 101
Time for acon – reading data from a text le 103
While loops 105
Parsing strings and extracng data 105
Alternave approach to reading from a text le 106
If statements and condional expressions 107
Storing data in a diconary 108
www.it-ebooks.info
Table of Contents
[ iv ]
Time for acon – dening and accessing diconaries 108
Lambda forms 110
Time for acon – using lambda to create an anonymous funcon 110
Summary 111
Chapter 5: Vectors, Matrices, and Linear Algebra 113
Vectors and vector spaces 113
Time for acon – working with vectors 114
Creang a vector space 115
Confusion alert: Sage plots and matplotlib 141
Plong in two dimensions 141
www.it-ebooks.info
Table of Contents
[ v ]
Plong symbolic expressions with Sage 142
Time for acon – plong symbolic expressions 142
Time for acon – plong a funcon with a pole 144
Time for acon – plong a parametric funcon 146
Time for acon – making a polar plot 147
Time for acon – plong a vector eld 149
Plong data in Sage 150
Time for acon – making a scaer plot 150
Time for acon – plong a list 151
Using graphics primives 153
Time for acon – plong with graphics primives 153
Using matplotlib 155
Time for acon – plong funcons with matplotlib 155
Using matplotlib to "tweak" a Sage plot 157
Time for acon – geng the matplotlib gure object 158
Time for acon – improving polar plots 159
Plong data with matplotlib 161
Time for acon – making a bar chart 161
Time for acon – making a pie chart 163
Time for acon – plong a histogram 164
Plong in three dimensions 165
Time for acon – make an interacve 3D plot 166
Higher quality output 167
Parametric 3D plong 168
Time for acon – parametric plots in 3D 168
Time for acon – calculang limits 193
Derivaves 195
Time for acon – calculang derivaves 195
Integrals 198
Time for acon – calculang integrals 198
Series and summaons 199
Time for acon – compung sums of series 199
Taylor series 200
Time for acon – nding Taylor series 200
Laplace transforms 202
Time for acon – compung Laplace transforms 202
Solving ordinary dierenal equaons 204
Time for acon – solving an ordinary dierenal equaon 204
Summary 206
Chapter 8: Solving Problems Numerically 207
Sage and NumPy 208
Solving equaons and nding roots numerically 208
Time for acon – nding roots of a polynomial 208
Finding minima and maxima of funcons 210
Time for acon – minimizing a funcon of one variable 210
Funcons of more than one variable 211
Time for acon – minimizing a funcon of several variables 211
Numerical approximaon of derivaves 213
Time for acon – approximang derivaves with dierences 213
Compung gradients 215
Time for acon – compung gradients 215
Numerical integraon 217
Time for acon – numerical integraon 217
www.it-ebooks.info
Table of Contents
Expanding our simulaon to other kinds of vehicles 258
Time for acon – creang a vehicle base class 258
Creang a package for our simulaon 263
Time for acon – creang a combat simulaon package 263
Potenal pialls when working with classes and instances 268
Time for acon – using class and instance aributes 269
Time for acon – more about class and instance aributes 270
Creang empty classes and funcons 272
Time for acon – creang empty classes and funcons 272
Handling errors gracefully 273
Time for acon – raising and handling excepons 274
www.it-ebooks.info
Table of Contents
[ viii ]
Excepon types 278
Creang your own excepon types 279
Time for acon – creang custom excepon types 279
Unit tesng 284
Time for acon – creang unit tests for the Tank class 284
Strategies for unit tesng 288
Summary 289
Chapter 10: Where to go from here 291
Typeseng equaons with LaTeX 291
Installing LaTeX 292
Time for acon – PDF output from the notebook interface 293
The view funcon in the interacve shell 297
LaTeX mark-up in the notebook interface 297
Time for acon – working with LaTeX markup in the notebook interface 297
Time for acon – pung it all together 300
Speeding up execuon 304
unnecessary to write your own rounes for numerical mathemacs in low-level languages
such as FORTRAN or C++. Mathemacal soware systems like Sage have highly opmized
funcons that implement common numerical operaons like integraon, solving ordinary
dierenal equaons, and solving systems of equaons.
Sage is a collecon of nearly 100 mathemacal soware packages, which are listed at
When possible, exisng tools
are integrated into Sage, rather than duplicang their funconality. The enre collecon of
tools can be downloaded and installed as a binary distribuon or compiled from source code.
The Python language provides a unied interface to all of the packages. Python is a high-
level, interpreted, object-oriented programming language that is already well established
in the research community. Users can interact with Sage through an interacve command-
line interface or a graphical notebook interface. Sage can also be used as a Python library or
embedded in LaTeX documents. Sage is "ocially" available for recent versions of OS X, Linux,
Solaris, and Open Solaris. It runs on Windows with the help of a virtual machine and it can
be used on other plaorms, with varying degrees of support. A current list of all the available
plaorms can be found at />www.it-ebooks.info
Preface
[ 2 ]
The mission statement of the Sage project is:
Creating a viable, free, open source alternative to Magma, Maple,
Mathematica, and Matlab.
If you are familiar with any of these commercial mathemacal soware systems, then you
already have a good idea what Sage does. Sage oers several advantages over its commercial
competors. Sage is free, open-source soware, released under the GNU Public License
version 2 or higher (GPLv2+). There is no cost to download and install Sage, whether you
want to put it on your personal computer, install it in a university teaching lab, or deploy
it on every workstaon in a company. This advantage is especially important in developing
countries. The GPL license also means that Sage is free, as in "freedom." There are no
restricons on how or where you use the soware, the license can never be revoked, and
there is no annual maintenance fee. Another advantage is that you have access to every
working with objects in Sage.
Chapter 4, Introducing Python and Sage covers how to: use lists and tuples to store
sequenal data; iterate with loops; construct logical tests with "if" statements; read and
write data les; and store heterogeneous data in diconaries.
Chapter 5, Vectors, Matrices, and Linear Algebra covers how to create and manipulate vector
and matrix objects; how Sage can take the tedious work out of linear algebra; learning about
matrix methods for compung eigenvalues, inverses, and decomposions; and geng
started with NumPy arrays and matrices for numerical calculaons.
Chapter 6, Plong with Sage covers how to plot funcons of one variable; making various
types of specialized 2D plots such as polar plots and scaer plots; using matplotlib to
precisely format 2D plots and charts; and making interacve 3D plots of funcons of two
variables.
Chapter 7, Making Symbolic Mathemacs Easy covers how to create symbolic funcons
and expressions, and learn to manipulate them; solve equaons and systems of equaons
exactly, and nd symbolic roots; automate calculus operaons like limits, derivaves, and
integrals; create innite series and summaons to approximate funcons; perform Laplace
transforms; and nd exact soluons to ordinary dierenal equaons.
Chapter 8, Solving Problems Numerically covers how to nd the roots of an equaon;
compute integrals and derivaves numerically; nd minima and maxima of funcons;
compute discrete Fourier transforms, and apply window funcons; numerically solve an
ordinary dierenal equaon (ODE), and systems of ODEs; use opmizaon techniques
to t curves and nd minima; and explore the probability tools in Sage.
Chapter 9, Learning Advanced Python Programming covers how to dene your own classes;
use inheritance to expand the usefulness of your classes; organize your class denions in
module les; bundle module les into packages; handle errors gracefully with excepons;
dene your own excepons for custom error handling; and use unit tests to make sure your
package is working correctly.
Chapter 10, Where to go from here covers how to export equaons as PNG and PDF
les; export vector graphics and typeset mathemacal expressions for inclusion in LaTeX
documents; use LaTeX to document Sage worksheets; speed up collision detecon using
www.it-ebooks.info
Preface
[ 5 ]
You will also nd some other learning aids in the book, including:
Pop quiz – heading
These are short mulple choice quesons intended to help you test your own understanding.
Have a go hero – heading
These set praccal challenges and give you ideas for experimenng with what you have
learned.
You will also nd a number of styles of text that disnguish between dierent kinds of
informaon. Here are some examples of these styles, and an explanaon of their meaning.
Code words in text are shown as follows: "We can use the
help funcon to learn more
about it."
A block of code is set as follows:
print('This is a string')
print(1.0)
print(sqrt)
Any command-line input or output is wrien as follows:
sage: R = 250e3
sage: C = 4e-6
sage: tau = R * C
sage: tau
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "clicking the Next buon
moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
www.it-ebooks.info
Preface
be uploaded on our website, or added to any list of exisng errata, under the Errata secon
of that tle. Any exisng errata can be viewed by selecng your tle from
http://www.
packtpub.com/support
.
www.it-ebooks.info
Preface
[ 7 ]
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protecon of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the locaon
address or website name immediately so that we can pursue a remedy.
Please contact us at
with a link to the suspected pirated material.
We appreciate your help in protecng our authors, and our ability to bring you valuable
content.
Questions
You can contact us at if you are having a problem with any
aspect of the book, and we will do our best to address it.
www.it-ebooks.info
www.it-ebooks.info