sage - american mathematical societyviii contents 1.11.2. higher-orderderivatives 50 1.12....

29
Gregory V. Bard Sage for Undergraduates

Upload: others

Post on 15-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

Gregory V Bard

Sagefor Undergraduates

A M E R I C A N M A T H E M A T I C A L S O C I E T Y

Sagefor Undergraduates

A M E R I C A N M A T H E M A T I C A L S O C I E T Y

Providence Rhode Island

Gregory V Bard

Sagefor Undergraduates

httpdxdoiorg101090mbk087

The Sage logo is under license as CC BY 40 found athttpcreativecommonsorglicensesby40

Used with permission

2010 Mathematics Subject Classification Primary 15-04 34-04 65-04 90-04 97M10Secondary 11-04 12-04 28-04 40-04 68U05

For additional information and updates on this book visitwwwamsorgbookpagesmbk-87

Library of Congress Cataloging-in-Publication Data

Bard Gregory VSage for undergraduates Gregory V Bard

pages cmISBN 978-1-4704-1111-4 (alk paper)1 AlgebramdashComputer programs 2 MathematicsmdashComputer programs I Title

QA1557E4B37 2015510285prime53mdashdc23

2014033572

Copying and reprinting Individual readers of this publication and nonprofit librariesacting for them are permitted to make fair use of the material such as to copy select pages foruse in teaching or research Permission is granted to quote brief passages from this publication inreviews provided the customary acknowledgment of the source is given

Republication systematic copying or multiple reproduction of any material in this publicationis permitted only under license from the American Mathematical Society Permissions to reuseportions of AMS publication content are handled by Copyright Clearance Centerrsquos RightsLinkservice For more information please visit httpwwwamsorgrightslink

Send requests for translation rights and licensed reprints to reprint-permissionamsorgExcluded from these provisions is material for which the author holds copyright In such cases

requests for permission to reuse or reprint material should be addressed directly to the author(s)Copyright ownership is indicated on the copyright page or on the lower right-hand corner of thefirst page of each article within proceedings volumes

ccopy 2015 by the American Mathematical Society All rights reservedPrinted in the United States of America

copyinfin The paper used in this book is acid-free and falls within the guidelinesestablished to ensure permanence and durability

Visit the AMS home page at httpwwwamsorg

10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15

With warmth I dedicate this book to my husband Patrick who hassupported me throughout my career in good years and in bad years andwho has spent many evenings alone because I was working on this book

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 2: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

A M E R I C A N M A T H E M A T I C A L S O C I E T Y

Sagefor Undergraduates

A M E R I C A N M A T H E M A T I C A L S O C I E T Y

Providence Rhode Island

Gregory V Bard

Sagefor Undergraduates

httpdxdoiorg101090mbk087

The Sage logo is under license as CC BY 40 found athttpcreativecommonsorglicensesby40

Used with permission

2010 Mathematics Subject Classification Primary 15-04 34-04 65-04 90-04 97M10Secondary 11-04 12-04 28-04 40-04 68U05

For additional information and updates on this book visitwwwamsorgbookpagesmbk-87

Library of Congress Cataloging-in-Publication Data

Bard Gregory VSage for undergraduates Gregory V Bard

pages cmISBN 978-1-4704-1111-4 (alk paper)1 AlgebramdashComputer programs 2 MathematicsmdashComputer programs I Title

QA1557E4B37 2015510285prime53mdashdc23

2014033572

Copying and reprinting Individual readers of this publication and nonprofit librariesacting for them are permitted to make fair use of the material such as to copy select pages foruse in teaching or research Permission is granted to quote brief passages from this publication inreviews provided the customary acknowledgment of the source is given

Republication systematic copying or multiple reproduction of any material in this publicationis permitted only under license from the American Mathematical Society Permissions to reuseportions of AMS publication content are handled by Copyright Clearance Centerrsquos RightsLinkservice For more information please visit httpwwwamsorgrightslink

Send requests for translation rights and licensed reprints to reprint-permissionamsorgExcluded from these provisions is material for which the author holds copyright In such cases

requests for permission to reuse or reprint material should be addressed directly to the author(s)Copyright ownership is indicated on the copyright page or on the lower right-hand corner of thefirst page of each article within proceedings volumes

ccopy 2015 by the American Mathematical Society All rights reservedPrinted in the United States of America

copyinfin The paper used in this book is acid-free and falls within the guidelinesestablished to ensure permanence and durability

Visit the AMS home page at httpwwwamsorg

10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15

With warmth I dedicate this book to my husband Patrick who hassupported me throughout my career in good years and in bad years andwho has spent many evenings alone because I was working on this book

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 3: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

A M E R I C A N M A T H E M A T I C A L S O C I E T Y

Providence Rhode Island

Gregory V Bard

Sagefor Undergraduates

httpdxdoiorg101090mbk087

The Sage logo is under license as CC BY 40 found athttpcreativecommonsorglicensesby40

Used with permission

2010 Mathematics Subject Classification Primary 15-04 34-04 65-04 90-04 97M10Secondary 11-04 12-04 28-04 40-04 68U05

For additional information and updates on this book visitwwwamsorgbookpagesmbk-87

Library of Congress Cataloging-in-Publication Data

Bard Gregory VSage for undergraduates Gregory V Bard

pages cmISBN 978-1-4704-1111-4 (alk paper)1 AlgebramdashComputer programs 2 MathematicsmdashComputer programs I Title

QA1557E4B37 2015510285prime53mdashdc23

2014033572

Copying and reprinting Individual readers of this publication and nonprofit librariesacting for them are permitted to make fair use of the material such as to copy select pages foruse in teaching or research Permission is granted to quote brief passages from this publication inreviews provided the customary acknowledgment of the source is given

Republication systematic copying or multiple reproduction of any material in this publicationis permitted only under license from the American Mathematical Society Permissions to reuseportions of AMS publication content are handled by Copyright Clearance Centerrsquos RightsLinkservice For more information please visit httpwwwamsorgrightslink

Send requests for translation rights and licensed reprints to reprint-permissionamsorgExcluded from these provisions is material for which the author holds copyright In such cases

requests for permission to reuse or reprint material should be addressed directly to the author(s)Copyright ownership is indicated on the copyright page or on the lower right-hand corner of thefirst page of each article within proceedings volumes

ccopy 2015 by the American Mathematical Society All rights reservedPrinted in the United States of America

copyinfin The paper used in this book is acid-free and falls within the guidelinesestablished to ensure permanence and durability

Visit the AMS home page at httpwwwamsorg

10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15

With warmth I dedicate this book to my husband Patrick who hassupported me throughout my career in good years and in bad years andwho has spent many evenings alone because I was working on this book

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 4: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

The Sage logo is under license as CC BY 40 found athttpcreativecommonsorglicensesby40

Used with permission

2010 Mathematics Subject Classification Primary 15-04 34-04 65-04 90-04 97M10Secondary 11-04 12-04 28-04 40-04 68U05

For additional information and updates on this book visitwwwamsorgbookpagesmbk-87

Library of Congress Cataloging-in-Publication Data

Bard Gregory VSage for undergraduates Gregory V Bard

pages cmISBN 978-1-4704-1111-4 (alk paper)1 AlgebramdashComputer programs 2 MathematicsmdashComputer programs I Title

QA1557E4B37 2015510285prime53mdashdc23

2014033572

Copying and reprinting Individual readers of this publication and nonprofit librariesacting for them are permitted to make fair use of the material such as to copy select pages foruse in teaching or research Permission is granted to quote brief passages from this publication inreviews provided the customary acknowledgment of the source is given

Republication systematic copying or multiple reproduction of any material in this publicationis permitted only under license from the American Mathematical Society Permissions to reuseportions of AMS publication content are handled by Copyright Clearance Centerrsquos RightsLinkservice For more information please visit httpwwwamsorgrightslink

Send requests for translation rights and licensed reprints to reprint-permissionamsorgExcluded from these provisions is material for which the author holds copyright In such cases

requests for permission to reuse or reprint material should be addressed directly to the author(s)Copyright ownership is indicated on the copyright page or on the lower right-hand corner of thefirst page of each article within proceedings volumes

ccopy 2015 by the American Mathematical Society All rights reservedPrinted in the United States of America

copyinfin The paper used in this book is acid-free and falls within the guidelinesestablished to ensure permanence and durability

Visit the AMS home page at httpwwwamsorg

10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15

With warmth I dedicate this book to my husband Patrick who hassupported me throughout my career in good years and in bad years andwho has spent many evenings alone because I was working on this book

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 5: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

With warmth I dedicate this book to my husband Patrick who hassupported me throughout my career in good years and in bad years andwho has spent many evenings alone because I was working on this book

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 6: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

Contents

Preface How to Use This Book xv

Acknowledgements xix

Chapter 1 Welcome to Sage 111 Using Sage as a Calculator 112 Using Sage with Common Functions 313 Using Sage for Trigonometry 714 Using Sage to Graph 2-Dimensionally 9141 Controlling the Viewing Window of a Plot 11142 Superimposing Multiple Graphs in One Plot 1515 Matrices and Sage Part 1 19151 A First Taste of Matrices 19152 Complications in Converting Linear Systems 20153 Doing the RREF in Sage 22154 Basic Summary 24155 The Identity Matrix 25156 A Challenge to Practice by Yourself 25157 Vandermondersquos Matrix 26158 The Semi-Rare Cases 2816 Making Your Own Functions in Sage 3017 Using Sage to Manipulate Polynomials 3418 Using Sage to Solve Problems Symbolically 37181 Solving Single-Variable Formulas 37182 Solving Multivariable Formulas 38183 Linear Systems of Equations 39184 Non-Linear Systems of Equations 40185 Advanced Cases 4319 Using Sage as a Numerical Solver 44110 Getting Help When You Need It 47111 Using Sage to Take Derivatives 491111 Plotting f(x) and f prime(x) Together 50

vii

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 7: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

viii CONTENTS

1112 Higher-Order Derivatives 50112 Using Sage to Calculate Integrals 51113 Sharing the Results of Your Work 60

Chapter 2 Fun Projects Using Sage 6321 Microeconomics Computing a Selling Price 6422 Biology Clogged Arteries and Poiseuillersquos Law 6923 Industrial Optimization Shipping Taconite 7224 Chemistry Balancing Reactions with Matrices 73241 Background 74242 Five Cool Examples 75243 The Slow Way Deriving the Method 75244 Balancing the Quick Way 7725 Physics Ballistic Projectiles 79251 Our First Example of Ballistic Trajectories 80252 Our Second Example of Ballistic Trajectories 82253 Counter-Battery Fire 83254 Your Challenge A Multi-Stage Rocket 8426 Cryptology Pollardrsquos pminus 1 Attack on RSA 85261 Background B-Smooth Numbers and B 86262 The Theory behind the Attack 87263 Computing 2(B) mod N 88264 Your Challenge Make All This Happen in Sage 90265 Safeguards against Pollardrsquos Factorial Attack 9027 Mini-Project on Electric Field Vector Plots 91

Chapter 3 Advanced Plotting Techniques 9331 Annotating Graphs for Clarity 93311 Labeling the Axes of Graphs 93312 Grids and Graphing Calculator-Style Graphs 95313 Adding Arrows and Text to Label Features 96314 Graphing an Integral 97315 Dotted and Dashed Lines 9832 Graphs of Some Hyperactive Functions 9933 Polar Plotting 100331 Examples of Polar Graphs 102332 Problems That Can Occasionally Happen 10234 Graphing an Implicit Function 10435 Contour Plots and Level Sets 106351 An Application to Thermodynamics 109352 Application to Microeconomics (Cobb-Douglas Equations) 11236 Parametric 2D Plotting 11437 Vector Field Plots 116371 Gradients and Vector Field Plots 117372 An Application from Physics 118

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 8: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

CONTENTS ix

373 Gradients versus Contour Plot 12138 Log-Log Plots 12239 Rare Situations 124

Chapter 4 Advanced Features of Sage 12941 Using Sage with Multivariable Functions and Equations 12942 Working with Large Formulas in Sage 131421 Personal Finance Mortgages 131422 Physics Gravitation and Satellites 13443 Derivatives and Gradients in Multivariate Calculus 136431 Partial Derivatives 136432 Gradients 13744 Matrices and Sage Part 2 137441 Defining Some Examples 137442 Matrix Multiplication and Exponentiation 138443 Right and Left System Solving 139444 Matrix Inverses 141445 Computing the Kernel of a Matrix 143446 Determinants 14545 Vector Operations 14646 Working with the Integers and Number Theory 147461 The gcd and the lcm 147462 More about Prime Numbers 149463 About Eulerrsquos Phi Function 149464 The Divisors of a Number 151465 Another Meaning for tau 153466 Modular Arithmetic 154467 Further Reading in Number Theory 15547 Some Minor Commands of Sage 155471 Rounding Floors and Ceilings 155472 Combinations and Permutations 155473 The Hyperbolic Trigonometric Functions 15748 Calculating Limits Expressly 15849 Scatter Plots in Sage 159410 Making Your Own Regressions in Sage 163411 Computing in Octal Binary And Hexadecimal 165412 Can Sage Do Sudoku 165413 Measuring the Speed of Sage 166414 Huge Numbers and Sage 167415 Using Sage and LATEX 168416 Matrices and Sage Part 3 1694161 Introduction to Eigenvectors 1694162 Finding Eigenvalues Efficiently in Sage 1714163 Matrix Factorizations 1724164 Solving Linear Systems Approximately with Least Squares 173

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 9: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

x CONTENTS

417 Computing Taylor or MacLaurin Polynomials 1754171 Examples of Taylor Polynomials 1764172 An Application Understanding How g Changes 177418 Minimizations and Lagrange Multipliers 1794181 Unconstrained Optimization 1794182 Constrained Optimization by Lagrange Multipliers 1814183 A Lagrange Multipliers Example in Sage 1814184 Some Applied Problems 183419 Infinite Sums and Series 1844191 Verifying Summation Identities 1854192 The Geometric Series 1864193 Using Sage to Guide a Summation Proof 187420 Continued Fractions in Sage 188421 Systems of Inequalities and Linear Programming 1894211 A Simple Example 1904212 Convenient Features in Practice 1924213 The Polyhedron of a 3-Variable Linear Program 1944214 Integer Linear Programs and Boolean Variables 1944215 Further Reading on Linear Programming 195422 Differential Equations 1954221 Some Easy Examples 1964222 An Initial-Value Problem 1984223 Graphing a Slope Field 1994224 The Torpedo Problem Working with Parameters 201423 Laplace Transforms 2034231 Transforming from f(t) to L(s) 2034232 Computing the Laplace Transform ldquothe Long Wayrdquo 2044233 Transforming from L(s) to f(t) 205424 Vector Calculus in Sage 2064241 Notation for Vector-Valued Functions 2064242 Computing the Hessian Matrix 2074243 Computing the Laplacian 2084244 The Jacobian Matrix 2094245 The Divergence 2104246 Verifying an Old Identity 2114247 The Curl of a Vector-Valued Function 2124248 A Challenge Verifying Some Curl Identities 2164249 Multiple Integrals 216

Chapter 5 Programming in Sage and Python 21951 Repetition without Boredom The For Loop 220511 Using Sage to Generate Tables 220512 Carefully Formatting the Output 221513 Arbitrary Lists 222514 Loops with Accumulators 223

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 10: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

CONTENTS xi

515 Using Sage to Find a Limit Numerically 224516 For Loops and Taylor Polynomials 226517 If You Already Know How to Program 22752 Writing Subroutines 228521 An Example Working with Coinage 228522 A Challenge A Cash Register 230523 An Example Designing Aquariums 231524 A Challenge A Cylindrical Silo 233525 Combining Loops and Subroutines 233526 Another Challenge Totaling a Sequence 23453 Loops and Newtonrsquos Method 235531 What Is Newtonrsquos Method 235532 Newtonrsquos Method with a For Loop 238533 Testing the Code 239534 Numerical versus Exact Representations 241535 Working with Optional and Mandatory Parameters 242536 Returning a Value and Nesting Subroutines 244537 A Challenge Finding a Point of Agreement 246538 A Challenge Finding Parallel Tangent Lines 246539 A Challenge Halleyrsquos Method 24854 An Introduction to Control Flow 249541 Verbosity Control 249542 Theoretical Interlude When Newtonrsquos Method Goes Crazy 251543 Stopping Newtonrsquos Method Early 254544 The List of Comparators 257545 A Challenge How Many Primes Are Less Than x 25755 More Concepts in Flow Control 258551 Raising an ldquoExceptionrdquo 258552 The If-Then-Else Construct 260553 Easy Challenge Registrarrsquos End of Semester Run Part 1 262554 A Harder Challenge Registrarrsquos End of Semester Run

Part 2 26256 While Loops versus For Loops 263561 A Question about Factorials 263562 A Challenge Finding the Next Prime Number 264563 Newtonrsquos Method with a While Loop 264564 The Impact of Repeated Roots 265565 Factorization by Trial Division 267566 A Mini-Challenge Trial Division Stopping Early 268567 A Challenge An Upgraded Cash Register 26957 How Arrays and Lists Work 270571 Lists of Points and Plotting 270572 A Challenge Making the Plot Command 272573 Operations on Lists 272574 Looping through an Array 274

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 11: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

xii CONTENTS

575 A Challenge A Company Profit Report 275576 Averaging Some Numbers 276577 Mini-Challenge Averaging Both with and without

Dropping 277578 Mini-Challenge Doubling Counting the Highest Quiz 277579 A Challenge Registrarrsquos End of Semester Run Part 3 2775710 A Utility Returning Only Real Rational or Integer

Roots 27858 Where Do You Go from Here 279581 Further Resources on Python Programming 279582 What Has Been Left Out 280

Chapter 6 Building Interactive Webpages with Sage 28561 The Six-Stage Process for Building Interacts 28662 The Tangent-Line Interact 287Stage 0 Develop a Concept 287Stage 1 Design a Sage Subroutine 288Stage 2 Polish This Subroutine 290Stage 3 Convert to an Interactive Subroutine 291Stage 4 Insert into a Web Template 292Stage 5 Flesh-Out the Webpage 29563 A Challenge to the Reader 29564 The Optimal Aquarium Interact 29565 Selectors and Checkboxes 29666 The Definite Integral Interact 297

Appendix A What to Do When Frustrated 299

Appendix B Transitioning to SageMathCloud 305B1 What Is SageMathCloud 305B2 Getting Started in SageMathCloud 306B3 Other Cloud Features 307

Appendix C Other Resources for Sage 309

Appendix D Linear Systems with Infinitely Many Solutions 313D1 The Opening Example 313D2 Another Example 316D3 Exploring Deeper 318D31 An Interesting Re-Examination of Unique Solutions 318D32 Two Equations and Four Unknowns 319D33 Two Equations and Four Unknowns but No Solutions 319D34 Four Equations and Three Unknowns 320D4 Misconceptions 320D5 Formal Definitions of REF and RREF 321D6 Alternative Notation 322D7 Geometric Interpretations in Three Dimensions 322

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 12: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

CONTENTS xiii

D71 Visualization of These Cases 323D72 Geometric Interpretations in Higher Dimensions 324D8 Dummy-Variable Notation 324D9 Solutions to Challenges 325

Appendix E Installing Sage on Your Personal Computer 327

Appendix F Index of Commands by Section and by Name 331

List of References 351

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 13: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

PrefaceHow to Use This Book

As the open-source and free competitor to expensive software like MapleTMMathematica Magma and Matlab Sage offers anyone with access toa web browser the ability to use cutting-edge mathematical software anddisplay the results for others often with stunning graphics Irsquom sure thatyou will find Sage far easier to use than a graphing calculator and vastlymore powerful

There is no need to read this entire document just as you would neverread the dictionary cover to cover This book is ideal for self-study but ifyou are assigned this book as part of a class then your professor will tellyou which section numbers correspond to what you need to be reading

For other readers who are reading independently of a specific class Ihave the following suggestions

bull Chapter 1 contains the basicsmdashwhat you really need to know Mostof the common tasks in Sage were carefully designed to be as intu-itive as possible with notation as close as possible to how mathe-matics is done on the whiteboard or with a pencil I recommendthat you never try to read more than 3 entire sections in one dayOtherwise there is too much for your brain to absorb while stillkeeping the experience fun and new However 1ndash2 sections perday should be easily digestible

Note Personally I recommend just reading Chapter 1 and then startplaying around on your own The best way to learn a new bit

xv

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 14: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

xvi PREFACE HOW TO USE THIS BOOK

of computer software is to use it recreationally Using the table ofcontents or the index of commands (in Appendix F) you can alwayslook up how to do some task which you havenrsquot learned yet If youget flummoxed at any point be sure to check out Appendix AldquoWhat to Do When Frustratedrdquo

bull Chapter 2 contains projects where you can use Sage to solve math-ematics problems as they arise in other subjectsmdashcryptographyphysics chemistry biology and so forth These projects are pri-marily aimed to be tractable after reading Chapter 1 However insome cases another section from a higher numbered chapter will berequired also Of course in those cases the dependency is clearlymarked These projects are intended to be assigned over weekendsThey are not large enough to be semester projects but they aretoo large to be homework problems

bull Chapter 3 is all about making beautiful plots and graphs I haveincluded everything that I could However some types of plotssuch as 3D plots animated plots and multicolored plots cannotbe easily represented in a printed black-and-white book There-fore those types of plots are covered in the electronic-only onlineappendix to this book ldquoPlotting in Color in 3D and Animationsrdquoavailable on my webpage wwwgregorybardcom for downloadingby clicking on the link at the left of the screen for Sage

bull Chapter 4 is enormous and contains small sections that discussadvanced mathematical topics Sage can handle an extraordinaryvariety of math problems This chapter was designed so that theindividual sections can be read independently There is no need toread the sections in Chapter 4 in order unless you want to

bull Chapter 5 is about how to program in Python using Sage Asa computer algebra system Sage is built on top of the computerlanguage Python Therefore you can use Python commands inSage Sometimes this is really usefulmdashfor example you can writefor loops to make tables very easily At other times it is convenientto write entire computer programs in Python using Sage as theinterface This is even more true when using SageMathCloudTM

bull Chapter 6 covers making interactive webpages (called ldquoappsrdquo) usingSage The process is remarkably straightforward I have a six-stageprocess which Irsquove been using myself You can make extremelyinteresting interacts using Sage and Irsquoll bet yoursquoll be surprised athow easy it is to make your own

bull Appendix A is ldquoWhat to Do When Frustratedrdquo There I have a listof questions you should ask yourself if you get stuck in a situationwhere Sage is refusing to respond to your commands in the waythat yoursquod like In almost all cases one of the listed items willpresent you with a way of resolving the frustration

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 15: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

PREFACE HOW TO USE THIS BOOK xvii

bull Appendix B is about gaining familiarity with SageMathCloud andsome of its features Cloud computing is a new and exciting wayto compute using the Internet instead of your local machine as aplace for storing your files

Note Generally users will want to switch to SageMathCloud after com-pleting Chapter 1 before tackling the projects in Chapter 2 or theadvanced work of Chapters 4ndash6 I think the information in Chap-ter 3 can be learned before or after learning SageMathCloud withno disadvantage to the user

bull Appendix C is a collection of further resources on Sage for readerswho would like to learn more than this book contains

bull Appendix D is my response to the fact that students often do nothave facility with systems of linear equations that have an infinitenumber of solutions This concept is often grasped as an idea butthe details are often not there when I need students to know themTherefore I have decided to be hyper-thorough and devote a largenumber of pages to explaining this (admittedly difficult) subject Ihope it will be useful to students

bull Appendix E is what you should read if you want to learn how toinstall Sage on your local machine

bull Appendix F is an eighteen()-page index of all the commands inthis book for your reference Special thanks to Thomas Suiterwho prepared it

bull The online electronic appendix will cover plotting in color anima-tions and 3D graphics Those subjects are not suited to a black-and-white book and therefore cannot be printed within these coversYou can download that from my webpage

wwwgregorybardcom

by clicking on the link at the left of the screen for Sage

Letrsquos Dive In Right Now

Without any hesitation whatsoever open up a web browser at this verymoment Type in the following URL

httpssagecellsagemathorg

You have now connected to the ldquoSage Cell Serverrdquo Now you shall seea large window (called a cell) and a big button marked ldquoEvaluaterdquo In thatcell type

solve( x^2 - 16 == 0 x )

and then click ldquoEvaluaterdquoYou should receive back the answer

[x == -4 x == 4]

which is clearly the correct set of two solutions to the equation x2 minus 16 = 0You have now solved your first math problem with Sage Congratulations

Welcome to Sage You are now ready to begin reading Chapter 1

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 16: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

Acknowledgements

First I would like to thank William Stein the creator of Sage for his en-couragement assistance and access to supercomputing resources which havemade my cryptanalytic research possible Professor Stein is the founder ofSage its chief architect and organizer and the source of enthusiasm forthe Sage communitymdashwhich by this point now includes hundreds of peopleacross many countries and continents Many of the original lines of Sageitself as well as the vast majority of SageMathCloud were personally codedby Professor Stein

This book began as ldquoA Guide to Sagerdquo while I was teaching for five weeksin Beijing at the Chinese Academy of Sciences Academy of Mathematicsand Systems Science Key Laboratory for Mathematics Mechanization dur-ing the summer of 2010 I am very grateful for being given that specialopportunity to work with such advanced students I was teaching fromanother book that I have written Algebraic Cryptanalysis published bySpringer in 2009 I gave several hours of instruction in Sage but it becameclear that having written instructions would be more useful for studentsOne can thumb through written pages while working on Sage and there-fore the document that would eventually become this book was born I amextraordinarily grateful for the opportunity to have visited that excellentinstitution When I left there this document was 37 pages long but fromtiny acorns do mighty oak trees grow

Like many researchers who invent a new algorithm as part of their PhDdissertations at the University of Maryland I had to write code to prove thatmy algorithm is effective correct and efficient However such code is oftendiscarded after the PhD is conferred I would like to thank Martin Albrechtwho first introduced me to the Sage community and who was instrumentalin the inclusion of my dissertation code into the Sage libraries in what hasbecome the M4RI project Without Martin Irsquod never had heard of Sage norwould my dissertation code be in use by people scattered about the worldAs it turns out M4RI is an evolving project continually upgraded by manydifferent researchers and today probably contains very few of my original

xix

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 17: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

xx ACKNOWLEDGEMENTS

lines That is an example of how software can evolve You can read aboutthe original algorithm in Chapter 9 of Algebraic Cryptanalysis

I would also like thank Robert Beezer and Robert Miller for giving meencouragement in using Sage in my teaching and research respectively Inparticular Robert Beezerrsquos outstanding (and free) ebook A First Course inLinear Algebra was an inspiration for me while writing this book

The Sage Cell Server has made Sage accessible to a much wider audiencethan has ever before been dreamed possible Even for those experiencedwith Sage the user experience is now vastly improved This important anddifficult work has been done by Jason Grout Ira Hanson Steven JohnsonAlex Kramer and William Stein Originally Sage was suitable for graduatestudents faculty and perhaps senior math majors Then the Sage NotebookServer came along bringing Sage to the mid-career undergraduate Nowthanks to the Sage Cell Server it is now appropriate to use Sage even inPrecalculus classes if desired

The American Mathematical Society was most flexible with me on thematters of deadlines as well as the many images in this textbook Produc-ing a book requires a surprisingly large number of steps and I am gratefulfor the support of Ina Mette the acquisitions editor and Marcia Almeidaher assistant I am particularly grateful for Inarsquos energetic and enthusias-tic encouragement that I turn what was once a small guide into a larger(published) book This project would not exist without her encouragementFurthermore I am grateful for the many hours of work of Arlene OrsquoSean asproduction editor of this book correcting my numerous typos

I would like to thank Andrew Novocin for teaching me how to includepng files in LATEX documents which saved me the time of manually con-verting the file formats of the armada of screen captures that fill this bookI might have otherwise abandoned this entire book project

No author can proofread his or her own work effectively but that isparticularly the case for me I am very grateful for the assistance of theproofreaders Joseph Robert Bertino Joseph Loeffler and Thomas Suiterwho have each made suggestions and corrections on portions of this doc-ument Of particular merit Thomas Suiter made the index of commandsand Joseph Bertino has nobly borne (without complaint) an enormous work-load from me through the last few yearsmdashboth from this book and otherprojects Of course any errors that remain are my responsibility

My first job after getting my PhD from the University of Maryland wasat Fordham University in the Bronx NY where I was appointed to one ofthe four-year ldquoPeter M Curran Visiting Assistant Professorshipsrdquo I madesome progress on this project during my time at Fordham after return-ing from my summer in China I received encouragement and suggestionsfrom Shaun Ault Melkana Brakalova Armand Brumer Michael Burr BillCampbell Janusz Golec Maryam Hastings William Hastings Nick KintosRobert Lewis Damian Lyons Ian Morrison Leonard Nissim Cris PoorBenjamin Shemmer Shapoor Vali and Kris Wolff Fred Marottorsquos book

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 18: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

ACKNOWLEDGEMENTS xxi

Introduction to Mathematical Modeling Using Discrete Dynamical Systemspublished by Cengage in 2005 was also an inspiration for this work thoughI did not have the opportunity to discuss our areas of common interestwith him very often Jack Kamis Mila Martynovsky and Michael ldquoMishardquoZigelbaum provided me with valuable and practical teaching advice

In particular Shapoor Vali and I wrote our books at roughly the sametime so we endured the struggle of writing book chapters proofreadingdrafts and drawing up book proposals simultaneously We have both crosseda great desert not without pain and suffering and now we can both enjoythe oasis on the other side His book on mathematical economics is listedin the List of References

Many Fordham undergraduates gave me a great many tips correctionsopportunities for improvement and ideas At the risk of accidentally ex-cluding someone I wish to mention the following Fordham students JamesCompagnoni Gray Crenshaw Dan DiPasquale Patrick Fox Alex GolecSimon Kaluza Kyle Kloster Peter Muller Luigi Patruno Seena Vali andSean Woodward Much encouragement was also given by Ed Casimiro forwhich I am grateful

After the four-year position at Fordham had elapsed I had the greatluck of being hired at the University of WisconsinndashStout the polytechnicof the University of Wisconsin system This was a great boon for me asI received my undergraduate degree in Computer amp Systems Engineeringfrom Rensselaer Polytechnic Institute in 1999 and similarly my father re-ceived his undergraduate degree in Mechanical Engineering from ETH inZurich (the polytechnic of Switzerland) back in 1951 Accordingly return-ing to the atmosphere of a polytechnic was somewhat like coming homeWhile the three institutions are far from being identical triplets the noblegoal of preparing hard-working students to become engineers scientists andmanagers or members of other lucrative technical professions creates an at-titude of focus on the pragmatic on hard work and on exactitude Thisldquopolytechnic attituderdquo is reflected across the spectrum of academic rankfrom the Chancellor to the freshmen It breeds respect for mathematics ingeneral and calculus in particular At UWndashStout mathematics is seen as abridge to important career-related coursework and not as a mere barrier tograduation

The vast vast majority of this book was written while working for UWndashStout Both Dean Jeffery Anderson and Dean Charles Bomar provided ad-ministrative financial and emotional support for this project The degreeof cooperation in our Department of Mathematics Statistics and ComputerScience (MSCS) is extremely rare and heartwarming Unless I am verymuch mistaken every last member of the department has contributed tothis book via a suggestion correction comment filling in for me in classwhen I was away at a conference or by giving encouragement Teaching

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 19: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

xxii ACKNOWLEDGEMENTS

24 credits per year in a climate thoroughly unfriendly1 to human habitationwhile attempting to maintain some fraction of a research life has brought ustogether With great respect I inscribe their names here at this time AnneAntonippillai Wan Bae Alexander Basyrov Chairman Christopher Ben-del Seth Berrier Jeffrey Boerner Diane Christie Steven Deckelman BrentDingle Seth Dutter Jeanne Foley Eugen ldquoAndrerdquo Ghenciu Petre ldquoNelurdquoGhenciu Nasser Hadidi Matt Horak Ayub Hossain Amitava KarmakerDeborah Kruschwitz-List Terrence Mason Valentina ldquoDianardquo PostelnicuLaura Schmidt Loretta Thielman Peter Thielman Keith Wojciechowskiand Mingshen Wu Additionally the former faculty members Joy BeckerJohn Hunt Benjamin Jones Dennis Mikkelson and Eileen Zito have pro-vided advice encouragement or course materials Furthermore several ofour temporary hires have voluntarily taken upon themselves either phenom-enally unpleasant courses or the elevated obligations of full-time facultywithout additional financial compensation and are therefore particularlypraiseworthy Jim Church Brian Knaeble Shing Lee Olga LopukhovaJohn Neiderhauser Mark Pedersen and Dennis Schmidt The chairmanChris Bendel is particularly dedicated and an outstanding peacemaker whohas created a work environment of collaboration cooperation and mutualrespect often dreamed of In MSCS we labor to assist one another

Outside of my department at UWndashStout Alan Block Mark FentonJulie Furst-Bowe Sue Foxwell Jennifer Grant Mary Hopkins-Best MichaelLevy Steve Nold Marlann Patterson and Todd Zimmermann have given mebountiful encouragement I would also like to thank the entire Departmentof Biology which has set a very high standard of scholarship of interac-tive teaching of skilled grant-writing of innovative and laboratory-focusedcoursework and which has taught us all to get undergraduates heavily andmaterially involved in research

It would be customary to list here the students at UWndashStout who haveenriched my teaching and given me useful feedback Such a list would se-riously lengthen the book however I have been very lucky in that I havebeen assigned highly applied courses with content extremely applicable toprofessional practice in both engineering and management You will seethis effect in the body of this book as many examples will be drawn fromphysics and economics in concordance with the professional aspirations ofmy students The vast majority of my students at some time or another havegiven me a suggestion a correction or shown me some new application ofmathematics to their chosen fields of study I have studied and taught atother institutions but this phenomenon is one that I have only encounteredat UWndashStout and at Oxford in the UK when I was a visiting student there

1This is not an exaggeration Two examples will have to suffice On the first dayof classes in 2014 namely January 28 as I was leaving the house to go to campusweathercom gave a temperature of minus22F on the thermometer and minus41F with thewindchill For my metric readers that is minus294C on the thermometer and minus406C withthe windchill On May 2 and May 3 2013 we had 17 inches of snow (thatrsquos 432 cm)

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 20: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

ACKNOWLEDGEMENTS xxiii

Since I am unable to list all the students by name I will thank them bycourse number Math-123 Finite and Financial Mathematics Math-154Calculus II Math-380580 Cryptography Math-447747 Numerical Anal-ysis II and CS-480680 Computer Security

Previous to teaching at Fordham I had the opportunity to adjunct atAmerican University in Washington DC I would like to thank MichaelGray Angela Wu Nate Harshman and Michael Black for their supportencouragement assistance and mentoring as well as the alumnus AlexanderIvanov for his encouragement and personal energy

In addition to the faculty at universities where I have been teachingthe faculty of Columbia University and of the City University of New York(CUNY) two of the best institutions in ldquothe cityrdquo and the nation have givenme great help I have enjoyed conversations on both research and teach-ing with David Allen David Bayer Maria Chudnovsky Kenneth KramerHunter Johnson and Vladimir Shpilrain

In physics and in chemistry I have had the tremendous benefit of con-sulting experts For physics it was Gabriel Hannah and for chemistry itwas Gergely Sirokman They have checked their relevant sections carefullyand therefore the reader can be confident that those sections are free ofmistakes with one exception In the physics problems I have not carriedthe units through the formulas and into equations as is required by thatsubject In applied mathematics we generally do not do this and it wouldbe highly disorienting and tedious for me to modify this already-completedbook to match the convention of physicists

I have received a great deal of encouragement in this project includ-ing detailed suggestions from those listed above as well as Ron BannonMartin Brock Bruce Cohen Carmi Gressel Marshall Hampton BenjaminJones David Joyner Craig Larson Andrey Novoseltsev Clement Pernetand Susan Schmoyer

My former dissertation advisor and trusted friend Lawrence Washingtonhas inspired me with his extremely successful textbooks He has set a veryhigh bar for the rest of us to aspire to I frequently recommend Cryptographywith Coding Theory by Wade Trappe and Lawrence Washington to anyonewho wants to learn cryptographymdashfrom the undergraduate sophomore tothe senior faculty member

The WeBWorK community has worked closely with the Sage communityWeBWorK is the free open-source competitor to the online homework sys-tems run by textbook publishing houses and is endorsed by the Mathemat-ical Association of America Numerous hours of the lives of the WeBWorKvolunteers have been devoted to writing and maintaining the WeBWorKsystem as well as coding math problems For the integration with Sage thecommunity is heavily indebted to John Travis of Mississippi College whoactively contributes to both communities

The funding for Sage comes in large part from the National Science Foun-dation and in particular the divisions listed below The Sage community is

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 21: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

xxiv ACKNOWLEDGEMENTS

grateful for the support of the National Science Foundation grants

bull DMS-0545904 Division of Mathematical Sciences ldquoCAREER Co-homological Methods in Algebraic Geometry and Number Theoryrdquo

bull DMS-0555776 Division of Mathematical Sciences ldquoExplicit Ap-proaches to Modular Forms and Modular Abelian Varietiesrdquo

bull DMS-0713225 Division of Mathematical Sciences ldquoSAGE Soft-ware for Algebra and Geometry Experimentationrdquo

bull DMS-0757627 Division of Mathematical Sciences ldquoFRG Lndashfunc-tions and Modular Formsrdquo

bull DMS-0821725 Division of Mathematical Sciences ldquo SCREMS TheComputational Frontiers of Number Theory Representation The-ory and Mathematical Physicsrdquo

bull DMS-0838212 Division of Mathematical SciencesldquoEMSW21ndashRTG Research Training Group on Inverse Problemsand Partial Differential Equationsrdquo

bull DMS-1015114 Division of Mathematical Sciences ldquoSage UnifyingMathematical Software for Scientists Engineers and Mathemati-ciansrdquo

bull DUE-1022574 Division of Undergraduate Education ldquoCollabora-tive Research UTMOST Undergraduate Teaching in Mathematicswith Open Software and Textbooksrdquo

bull ACI-1147463 Division of Advanced CyberInfrastructure ldquoCollabo-rative Research SI2-SSE Sage-Combinat Developing and SharingOpen Source Software for Algebraic Combinatoricsrdquo

as well as funding from Microsoft Sun Microsystems Enthought Inc andGoogle

As I mentioned earlier the Sage community is enormous with hundredsof developers in many countries of several continents Despite the above-mentioned financial support almost all of the work is performed on anentirely voluntary and unpaid basis For the sacrifice of free time on the partof so many people the entire Sage community is grateful in the extreme

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 22: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

List of References

John Adam Blood vessel branching Beyond the standard calculus problem MathematicsMagazine 84 (2011)

Gregory V Bard Algebraic cryptanalysis Springer 2009

Robert Beezer A first course in linear algebra self-published on the Lulu dot ComPlatform 2007

William Boyce and Richard DiPrima Elementary differential equations and boundaryvalue problems 9th ed Wiley 2009

Marek Capinski and Tomasz Zastawniak Mathematics for finance An introduction tofinancial engineering Springer Undergraduate Mathematics Series Springer 2003

Alexandre Casamayou Nathann Cohen Guillaume Connan Thierry Dumont LaurentFousse Franois Maltey Matthias Meulien Marc Mezzarobba Clement Pernet Nico-las M Thiery and Paul Zimmermann Calcul mathematique avec Sage The CreateSpaceIndependent Publishing Platform 2013

Alan Doerr and Kenneth Levasseur Applied discrete structures 10 2012

Jeffrey Elkner Allen B Downey and Chris Meyers How to think like a computer scien-tist Learning with Python Green Tea Press 2002

Paul Fishback Linear and non-linear programming with maple An interactiveapplications-based approach CRC Press 2010

Galileo Galilei and Stillman Drake Discoveries and opinions of galileo 24th ed Anchor1957

Jose M Gallardo Ecuaciones diferenciales ordinarias una introduccion con SAGEOPENLIBRA (etnassoft) 2011

William Granville and David Joyner Differential calculus and Sage The CreateSpaceIndependent Publishing Platform 2009

David Joyner Adventures with group theory Rubikrsquos cube merlinrsquos machine and othermathematical toys 2nd ed The Johns Hopkins University Press 2008

351

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 23: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

352 LIST OF REFERENCES

David Joyner and Marshall Hampton Introduction to differential equations using SageJohns Hopkins University Press 2012

David R Kohel Cryptography 2008

James S Kraft and Lawrence C Washington An introduction to number theory withcryptography Chapman amp Hall 2013

Paul Lutus Exploring mathematics with Sage

Fred Marotto Introduction to mathematical modelling using discrete dynamical systemsCengage 2005

Mike Pilgrim Dive into Python 3 2nd ed Apress 2009

Ronald Rardin Optimization in operations research Prentice Hall 1997

Herman C Schepler The chronology of pi Mathematical Magazine 23 (1950) no 3

Harry Moritz Schey Div grad curl and all that an informal text on vector calculus4th ed W W Norton and Company 2004

David Sklar and Bruce Cohen Just enough Python for numerical analysis

William Stein Elementary number theory Primes congruences and secrets A compu-tational approach Undergraduate Texts in Mathematics Springer 2008

William Stein et al Sage reference manual v63 2014

James Stewart Calculus 6th ed Thomson BrooksCole 2008

Alan Sultan Linear programming An introduction with applications The CreateSpaceIndependent Publishing Platform 2011

Soo Tan Calculus with early transcendentals 1st ed 2011

Wade Trappe and Lawrence C Washington Cryptography with coding theory Pearson2005

Lloyd Trefethen and David Bau Numerical linear algebra Society for Industrial andApplied Mathematics 1997

Shapoor Vali Principles of mathematical economics Atlantis Press 2013

Lawrence C Washington Elliptic curves Number theory and cryptography 2nd edChapman amp HallCRC 2008

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d

Page 24: Sage - American Mathematical Societyviii CONTENTS 1.11.2. Higher-OrderDerivatives 50 1.12. UsingSagetoCalculateIntegrals 51 1.13. SharingtheResultsofYourWork 60 Chapter2. FunProjectsUsingSage

MBK87

AMS on the Web wwwamsorg

For additional informationand updates on this book visit

wwwamsorgbookpagesmbk-87

Professor Bard has provided a valuable service by carefully explaining everything an undergraduate student of mathematics or a teacher of these topics needs to get started with Sage quickly and easily It will also be useful for any student or teacher of another STEM discipline There is an excellent mix of the most frequently used commands along with warnings about common pitfalls or caveats I highly recommend it for anyone new to Sage or who desires an overview of the systemrsquos impressive capabilities

mdashRobert A Beezer University of Puget Sound

This book is a sort of ldquoMissing Manualrdquo that explains how Sage can be used in a range of standard mathematics courses instead of targeting specialists like much existing Sage documentation The depth of content is very impressive and describesmdashin a single coherent narrativemdashhow to successfully use Sage for a wide swath of undergraduate applied topics

mdashWilliam Stein University of Washington Seattle

As the open-source and free competitor to expensive software like Mapletrade Mathematicareg Magma and MATLABreg Sage offers anyone with access to a web browser the ability to use cutting-edge mathematical software and display his or her results for others often with stunning graphics This book is a gentle introduction to Sage for undergraduate students toward the end of Calculus II (single-variable integral calculus) or higher-level course work such as Multivariate Calculus Differential Equations Linear Algebra or Math Modeling

The book assumes no background in computer science but the reader who fi nishes the book will have learned about half of a fi rst semester Computer Science I course including large parts of the Python programming language The audience of the book is not only math majors but also physics engineering fi nance statistics chemistry and computer science majors

Phot

o by

Pat

rick

Stu

ddar

d