
- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Start Sage
- •Installing Sage
- •Starting Sage
- •Prerequisites
- •Installation
- •Summary
- •Command history
- •Working with code
- •Arithmetic operators
- •Strings
- •Functions
- •Functions with keyword arguments
- •Objects
- •Summary
- •Python 2 and Python 3
- •Running scripts
- •Strings
- •List comprehensions
- •Storing data in a dictionary
- •Summary
- •Vectors and vector spaces
- •Creating a vector space
- •Vector operators and methods
- •Decomposing matrices
- •Summary
- •Using graphics primitives
- •Summary
- •Substitutions
- •Finding roots
- •Derivatives
- •Integrals
- •Series and summations
- •Summary
- •Computing gradients
- •Constrained optimization
- •Probability
- •Summary
- •Making our tanks move
- •Unit testing
- •Summary
- •Introducing Python decorators
- •Making interactive graphics
- •Summary
- •Index
Preface
Results matter, whether you are a mathematician, scientist, or engineer. The time that you spend doing tedious mathematical calculations could be spent in more productive ways. Sage is an open-source mathematical software system that helps you perform many mathematical tasks. There is no reason to compute integrals or perform algebraic manipulations by hand when software can perform these tasks more quickly and accurately (unless you are a student who is learning these procedures for the first time). Students can also benefit from mathematical software. The ability to plot functions and manipulate symbolic expressions easily can improve your understanding of mathematical concepts. Likewise, it is largely unnecessary to write your own routines for numerical mathematics in low-level languages such as FORTRAN or C++. Mathematical software systems like Sage have highly optimized functions that implement common numerical operations like integration, solving ordinary differential equations, and solving systems of equations.
Sageisacollectionofnearly100mathematicalsoftwarepackages,whicharelistedat
http://www.sagemath.org/links-components.html.Whenpossible,existingtools areintegratedintoSage,ratherthanduplicatingtheirfunctionality.Theentirecollectionof toolscanbedownloadedandinstalledasabinarydistributionorcompiledfromsourcecode. ThePythonlanguageprovidesaunifiedinterfacetoallofthepackages.Pythonisahigh- level,interpreted,object-orientedprogramminglanguagethatisalreadywellestablished intheresearchcommunity.UserscaninteractwithSagethroughaninteractivecommandlineinterfaceoragraphicalnotebookinterface.SagecanalsobeusedasaPythonlibraryor
embeddedinLaTeXdocuments.Sageis"officially"availableforrecentversionsofOSX,Linux, Solaris,andOpenSolaris.ItrunsonWindowswiththehelpofavirtualmachineanditcan beusedonotherplatforms,withvaryingdegreesofsupport.Acurrentlistofalltheavailable platformscanbefoundathttp://wiki.sagemath.org/SupportedPlatforms.

Preface
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 mathematical software systems, then you already have a good idea what Sage does. Sage offers several advantages over its commercial competitors. Sage is free, open-source software, 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 workstation 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 restrictions on how or where you use the software, the license can never be revoked, and there is no annual maintenance fee. Another advantage is that you have access to every line of source code, so you can see how every calculation is performed, and track exactly what changes are made from one version to the next. Unlike commercial software, the bug list for Sage is public, and it can be accessed at http://trac.sagemath.org/. Users are encouraged to participate in the development of Sage by reporting and fixing bugs, and contributing new capabilities. With bugs and source code open for public review, you can have a high degree of confidence that Sage will produce correct results.
ThisbookiswrittenforpeoplewhoarenewtoSage,andperhapsnewtomathematical softwarealtogether.Forthisreason,theexamplesinthebookemphasizeundergraduate-level mathematicssuchascalculus,linearalgebra,andordinarydifferentialequations.However, Sageiscapableofperformingadvancedmathematics,andithasbeencitedinover80 mathematicalpublications.Afulllistcanbefoundathttp://www.sagemath.org/librarypublications.html.Tobenefitfromthisbook,youshouldhavesomefundamental knowledgeofcomputerprogramming,butthePythonlanguagewillbeintroducedasneeded throughoutthebook.Thenextchapterwilltakeyouthroughsomeexamplesthatshowcasea smallsubsetofSage'scapabilities.
What this book covers
Chapter 1, What can You do with Sage? covers how Sage can be used for: making simple numerical calculations; performing symbolic calculations, solving systems of equations and ordinary differential equations; making plots in two and three dimensions; and analyzing experimental data and fitting models.
Chapter 2, Installing Sage covers how to install a binary version of Sage on Windows and install a binary version of Sage on OS X; install a binary version of Sage on GNU/Linux; compile Sage from source.
[ 2 ]

Preface
Chapter 3, Getting Started with Sage covers using the interactive shell; using the notebook interface; learning more about operators and variables; defining and using callable symbolic expressions; calling functions and making simple plots; defining your own functions; and working with objects in Sage.
Chapter 4, Introducing Python and Sage covers how to: use lists and tuples to store sequential data; iterate with loops; construct logical tests with "if" statements; read and write data files; and store heterogeneous data in dictionaries.
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 computing eigenvalues, inverses, and decompositions; and getting started with NumPy arrays and matrices for numerical calculations.
Chapter 6, Plotting with Sage covers how to plot functions of one variable; making various types of specialized 2D plots such as polar plots and scatter plots; using matplotlib to precisely format 2D plots and charts; and making interactive 3D plots of functions of two variables.
Chapter 7, Making Symbolic Mathematics Easy covers how to create symbolic functions and expressions, and learn to manipulate them; solve equations and systems of equations exactly, and find symbolic roots; automate calculus operations like limits, derivatives, and integrals; create infinite series and summations to approximate functions; perform Laplace transforms; and find exact solutions to ordinary differential equations.
Chapter 8, Solving Problems Numerically covers how to find the roots of an equation; compute integrals and derivatives numerically; find minima and maxima of functions; compute discrete Fourier transforms, and apply window functions; numerically solve an ordinary differential equation (ODE), and systems of ODEs; use optimization techniques to fit curves and find minima; and explore the probability tools in Sage.
Chapter 9, Learning Advanced Python Programming covers how to define your own classes; use inheritance to expand the usefulness of your classes; organize your class definitions in module files; bundle module files into packages; handle errors gracefully with exceptions; define your own exceptions 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 equations as PNG and PDF files; export vector graphics and typeset mathematical expressions for inclusion in LaTeX documents; use LaTeX to document Sage worksheets; speed up collision detection using NumPy vector operations; create a Python script that uses Sage functionality; and create interactive graphical examples in the notebook interface.
[ 3 ]

Preface
Whatyouneedforthisbook
Required:
Sage
If using Windows, VMWare Player or VirtualBox is also required. Recommended, but not strictly necessary: LaTeX
Optional, for building Sage from source on Linux: GCC, g++, make, m4, perl, ranlib, readline, and tar
Optional, for building Sage from source on OS X: XCode
A web browser is required to use the notebook interface
Whothisbookisfor
If you are an engineer, scientist, mathematician, or student, this book is for you. To get the most from Sage by using the Python programming language, we'll give you the basics of the language to get you started. For this, it will be helpful if you have some experience with basic programming concepts.
Conventions
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Timeforaction–heading
1.
2.
3.
Action 1
Action 2
Action 3
Instructions often need some extra explanation so that they make sense, so they are followed with:
What just happened?
This heading explains the working of tasks or instructions that you have just completed.
[ 4 ]

Preface
You will also find some other learning aids in the book, including:
Popquiz–heading
These are short multiple choice questions intended to help you test your own understanding.
Haveagohero–heading
These set practical challenges and give you ideas for experimenting with what you have learned.
You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "We can use the help function 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 written 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 button moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
[ 5 ]

Preface
Readerfeedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloadingtheexamplecode
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code— we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.
packtpub.com/support.
[ 6 ]

Preface
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection 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 location address or website name immediately so that we can pursue a remedy.
Pleasecontactusatcopyright@packtpub.com withalinktothesuspectedpiratedmaterial.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it.
[ 7 ]