Sage Beginner''''s Guide - Pdf 11

www.it-ebooks.info
Sage
Beginner's Guide
Unlock the full potenal of Sage for simplifying and
automang mathemacal compung
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 transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon 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 informaon about all of the
companies and products menoned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this informaon.
First published: May 2011
Producon 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 computaonal science
and engineering and use them to solve dicult problems. In parcular, he is interested
in developing tools to help biologists study living systems. Craig is commied to using,
developing, and promong open-source soware. He provides documentaon 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 opcal properes of human ssue, with a mixture of
Monte Carlo modeling, radio frequency design, and laser opcs. David was awarded his Ph.D.
in 1999 from University College London.
Although not a mathemacian, Dr. Kirkby has made extensive use of mathemacal soware.
Most of his experience has been with MathemacaTM 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 soware for modeling
transmission lines using nite dierence (
design of

You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers 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 entled 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 collecon of free technical arcles, sign up for a
range of free newsleers and receive exclusive discounts and oers on Packt books and eBooks.

Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's enre 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 enrely free books. Simply use your login credenals 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
Geng started 9
Using Sage as a powerful calculator 12
Symbolic mathemacs 14
Linear algebra 17

Downloading and decompressing source tarball 39
Building Sage 39
Installaon 39
Summary 39
Chapter 3: Geng Started with Sage 41
How to get help with Sage 41
Starng Sage from the command line 42
Using the interacve shell 43
Time for acon – doing calculaons on the command line 43
Geng help 45
Command history 46
Tab compleon 47
Interacvely tracing execuon 48
Using the notebook interface 48
Starng the notebook interface 49
Time for acon – doing calculaons with the notebook interface 52
Geng help in the notebook interface 54
Working with cells 54
Working with code 55
Closing the notebook interface 55
Displaying results of calculaons 56
Operators and variables 56
Arithmec operators 57
Numerical types 58
Integers and raonal numbers 58
Real numbers 59
Complex numbers 60
Symbolic expressions 60
Dening variables on rings 61
Combining types in expressions 62

List funcons and methods 87
Tuples: read-only lists 87
Time for acon – returning mulple values from a funcon 87
Strings 89
Time for acon – working with strings 90
Other sequence types 92
For loops 92
Time for acon – iterang over lists 92
Time for acon – compung a soluon to the diusion equaon 94
List comprehensions 99
Time for acon – using a list comprehension 99
While loops and text le I/O 101
Time for acon – saving data in a text le 101
Time for acon – reading data from a text le 103
While loops 105
Parsing strings and extracng data 105
Alternave approach to reading from a text le 106
If statements and condional expressions 107
Storing data in a diconary 108
www.it-ebooks.info
Table of Contents
[ iv ]
Time for acon – dening and accessing diconaries 108
Lambda forms 110
Time for acon – using lambda to create an anonymous funcon 110
Summary 111
Chapter 5: Vectors, Matrices, and Linear Algebra 113
Vectors and vector spaces 113
Time for acon – working with vectors 114
Creang a vector space 115

Confusion alert: Sage plots and matplotlib 141
Plong in two dimensions 141
www.it-ebooks.info
Table of Contents
[ v ]
Plong symbolic expressions with Sage 142
Time for acon – plong symbolic expressions 142
Time for acon – plong a funcon with a pole 144
Time for acon – plong a parametric funcon 146
Time for acon – making a polar plot 147
Time for acon – plong a vector eld 149
Plong data in Sage 150
Time for acon – making a scaer plot 150
Time for acon – plong a list 151
Using graphics primives 153
Time for acon – plong with graphics primives 153
Using matplotlib 155
Time for acon – plong funcons with matplotlib 155
Using matplotlib to "tweak" a Sage plot 157
Time for acon – geng the matplotlib gure object 158
Time for acon – improving polar plots 159
Plong data with matplotlib 161
Time for acon – making a bar chart 161
Time for acon – making a pie chart 163
Time for acon – plong a histogram 164
Plong in three dimensions 165
Time for acon – make an interacve 3D plot 166
Higher quality output 167
Parametric 3D plong 168
Time for acon – parametric plots in 3D 168

Time for acon – calculang limits 193
Derivaves 195
Time for acon – calculang derivaves 195
Integrals 198
Time for acon – calculang integrals 198
Series and summaons 199
Time for acon – compung sums of series 199
Taylor series 200
Time for acon – nding Taylor series 200
Laplace transforms 202
Time for acon – compung Laplace transforms 202
Solving ordinary dierenal equaons 204
Time for acon – solving an ordinary dierenal equaon 204
Summary 206
Chapter 8: Solving Problems Numerically 207
Sage and NumPy 208
Solving equaons and nding roots numerically 208
Time for acon – nding roots of a polynomial 208
Finding minima and maxima of funcons 210
Time for acon – minimizing a funcon of one variable 210
Funcons of more than one variable 211
Time for acon – minimizing a funcon of several variables 211
Numerical approximaon of derivaves 213
Time for acon – approximang derivaves with dierences 213
Compung gradients 215
Time for acon – compung gradients 215
Numerical integraon 217
Time for acon – numerical integraon 217
www.it-ebooks.info
Table of Contents

Expanding our simulaon to other kinds of vehicles 258
Time for acon – creang a vehicle base class 258
Creang a package for our simulaon 263
Time for acon – creang a combat simulaon package 263
Potenal pialls when working with classes and instances 268
Time for acon – using class and instance aributes 269
Time for acon – more about class and instance aributes 270
Creang empty classes and funcons 272
Time for acon – creang empty classes and funcons 272
Handling errors gracefully 273
Time for acon – raising and handling excepons 274
www.it-ebooks.info
Table of Contents
[ viii ]
Excepon types 278
Creang your own excepon types 279
Time for acon – creang custom excepon types 279
Unit tesng 284
Time for acon – creang unit tests for the Tank class 284
Strategies for unit tesng 288
Summary 289
Chapter 10: Where to go from here 291
Typeseng equaons with LaTeX 291
Installing LaTeX 292
Time for acon – PDF output from the notebook interface 293
The view funcon in the interacve shell 297
LaTeX mark-up in the notebook interface 297
Time for acon – working with LaTeX markup in the notebook interface 297
Time for acon – pung it all together 300
Speeding up execuon 304

unnecessary to write your own rounes for numerical mathemacs in low-level languages
such as FORTRAN or C++. Mathemacal soware systems like Sage have highly opmized
funcons that implement common numerical operaons like integraon, solving ordinary
dierenal equaons, and solving systems of equaons.
Sage is a collecon of nearly 100 mathemacal soware packages, which are listed at
When possible, exisng tools
are integrated into Sage, rather than duplicang their funconality. The enre collecon of
tools can be downloaded and installed as a binary distribuon or compiled from source code.
The Python language provides a unied 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 interacve command-
line interface or a graphical notebook interface. Sage can also be used as a Python library or
embedded in LaTeX documents. Sage is "ocially" 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 plaorms, with varying degrees of support. A current list of all the available
plaorms 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 mathemacal soware systems, then you
already have a good idea what Sage does. Sage oers several advantages over its commercial
competors. Sage is free, open-source soware, 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 workstaon 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
restricons on how or where you use the soware, 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
sequenal data; iterate with loops; construct logical tests with "if" statements; read and
write data les; and store heterogeneous data in diconaries.
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 compung eigenvalues, inverses, and decomposions; and geng
started with NumPy arrays and matrices for numerical calculaons.
Chapter 6, Plong with Sage covers how to plot funcons of one variable; making various
types of specialized 2D plots such as polar plots and scaer plots; using matplotlib to
precisely format 2D plots and charts; and making interacve 3D plots of funcons of two
variables.
Chapter 7, Making Symbolic Mathemacs Easy covers how to create symbolic funcons
and expressions, and learn to manipulate them; solve equaons and systems of equaons
exactly, and nd symbolic roots; automate calculus operaons like limits, derivaves, and
integrals; create innite series and summaons to approximate funcons; perform Laplace
transforms; and nd exact soluons to ordinary dierenal equaons.
Chapter 8, Solving Problems Numerically covers how to nd the roots of an equaon;
compute integrals and derivaves numerically; nd minima and maxima of funcons;
compute discrete Fourier transforms, and apply window funcons; numerically solve an
ordinary dierenal equaon (ODE), and systems of ODEs; use opmizaon techniques
to t curves and nd minima; and explore the probability tools in Sage.
Chapter 9, Learning Advanced Python Programming covers how to dene your own classes;
use inheritance to expand the usefulness of your classes; organize your class denions in
module les; bundle module les into packages; handle errors gracefully with excepons;
dene your own excepons 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 equaons as PNG and PDF
les; export vector graphics and typeset mathemacal expressions for inclusion in LaTeX
documents; use LaTeX to document Sage worksheets; speed up collision detecon 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 mulple choice quesons intended to help you test your own understanding.
Have a go hero – heading
These set praccal challenges and give you ideas for experimenng with what you have
learned.
You will also nd a number of styles of text that disnguish between dierent kinds of
informaon. Here are some examples of these styles, and an explanaon of their meaning.
Code words in text are shown as follows: "We can use the
help funcon 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 wrien 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 buon
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 exisng errata, under the Errata secon
of that tle. Any exisng errata can be viewed by selecng 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 protecon 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 locaon
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 protecng 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


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status