Doing Math with Python Use Programming to Explore Algebra Statistics Calculus and More 1st Edition Amit Saha download
Doing Math with Python Use Programming to Explore Algebra Statistics Calculus and More 1st Edition Amit Saha download
https://textbookfull.com/product/doing-math-with-python-use-
programming-to-explore-algebra-statistics-calculus-and-more-1st-
edition-amit-saha/
https://textbookfull.com/product/math-adventures-with-python-an-
illustrated-guide-to-exploring-math-with-code-1st-edition-peter-
farrell/
https://textbookfull.com/product/math-302-lecture-notes-linear-
algebra-and-multivariable-calculus-kenneth-l-kuttler/
https://textbookfull.com/product/functional-python-programming-
use-a-functional-approach-to-write-succinct-expressive-and-
efficient-python-code-3rd-edition-lott/
https://textbookfull.com/product/introduction-to-scientific-
programming-with-python-joakim-sundnes/
Programming with MicroPython Embedded Programming with
Microcontrollers and Python 1st Edition Nicholas H.
Tollervey
https://textbookfull.com/product/programming-with-micropython-
embedded-programming-with-microcontrollers-and-python-1st-
edition-nicholas-h-tollervey/
https://textbookfull.com/product/doing-things-with-things-the-
design-and-use-of-everyday-objects-1st-edition-dreier/
https://textbookfull.com/product/introduction-to-gis-programming-
and-fundamentals-with-python-and-arcgis-1st-edition-chaowei-yang/
https://textbookfull.com/product/programming-with-micropython-
embedded-programming-with-microcontrollers-and-python-first-
edition-nicholas-h-tollervey/
https://textbookfull.com/product/learn-to-program-with-small-
basic-an-introduction-to-programming-with-games-art-science-and-
math-early-access-1st-edition-marji/
DOING MATH
EXPLORE MATH
WITH CODE
Doing Math with Python shows you how to use • Write programs to find derivatives and integrate
WITH PYTHON
Python to delve into high school–level math topics functions U S E P R O G R A M M I N G T O E X P L O R E A L G E B R A ,
like statistics, geometry, probability, and calculus.
Creative coding challenges and applied examples help S T A T I S T I C S , C A L C U L U S , AND MORE!
You’ll start with simple projects, like a factoring
you see how you can put your new math and coding
program and a quadratic-equation solver, and then
skills into practice. You’ll write an inequality solver, plot
create more complex projects once you’ve gotten
gravity’s effect on how far a bullet will travel, shuffle a
the hang of things. AMIT SAHA
deck of cards, estimate the area of a circle by throwing
Along the way, you’ll discover new ways to explore 100,000 “darts” at a board, explore the relationship
math and gain valuable programming skills that you’ll between the Fibonacci sequence and the golden ratio,
use throughout your study of math and computer and more.
science. Learn how to:
Whether you’re interested in math but have yet to dip
• Describe your data with statistics, and visualize it into programming or you’re a teacher looking to bring
with line graphs, bar charts, and scatter plots programming into the classroom, you’ll find that Python
makes programming easy and practical. Let Python
• Explore set theory and probability with programs for
handle the grunt work while you focus on the math.
coin flips, dicing, and other games of chance
ABOUT THE AUTHOR
• Solve algebra problems using Python’s symbolic math
functions Amit Saha is a software engineer who has worked
for Red Hat and Sun Microsystems. He created and
• Draw geometric shapes and explore fractals like
maintains Fedora Scientific, a Linux distribution for
the Barnsley fern, the Sierpiński triangle, and the
scientific and educational users. He is also the author
Mandelbrot set
of Write Your First Program (Prentice Hall Learning).
COVERS PYTHON 3
T H E F I N E ST I N G E E K E N T E RTA I N M E N T ™
w w w.nostarch.com
b y Amit Sa ha
San Francisco
Doing Math with Python. Copyright © 2015 by Amit Saha.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
Printed in USA
First printing
19 18 17 16 15 1 2 3 4 5 6 7 8 9
ISBN-10: 1-59327-640-0
ISBN-13: 978-1-59327-640-9
For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other
product and company names mentioned herein may be the trademarks of their respective owners. Rather
than use a trademark symbol with every occurrence of a trademarked name, we are using the names only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution
has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any
liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or
indirectly by the information contained in it.
To Protyusha, for never giving up on me
Brief Contents
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Afterword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Conte nt s in De ta il
Acknowledgments xiii
Introduction xv
Who Should Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
What’s in This Book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
Scripts, Solutions, and Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
1
Working with Numbers 1
Basic Mathematical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Labels: Attaching Names to Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Different Kinds of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Working with Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Getting User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Handling Exceptions and Invalid Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Fractions and Complex Numbers as Input . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Writing Programs That Do the Math for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Calculating the Factors of an Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Generating Multiplication Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Converting Units of Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Finding the Roots of a Quadratic Equation . . . . . . . . . . . . . . . . . . . . . . . . . . 20
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
#1: Even-Odd Vending Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
#2: Enhanced Multiplication Table Generator . . . . . . . . . . . . . . . . . . . . . . . . 23
#3: Enhanced Unit Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
#4: Fraction Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
#5: Give Exit Power to the User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2
Visualizing Data with Graphs 27
Understanding the Cartesian Coordinate Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Working with Lists and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Iterating over a List or Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Creating Graphs with Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Marking Points on Your Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Graphing the Average Annual Temperature in New York City . . . . . . . . . . . . . 35
Comparing the Monthly Temperature Trends of New York City . . . . . . . . . . . . 38
Customizing Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Saving the Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Plotting with Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Newton’s Law of Universal Gravitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Projectile Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
#1: How Does the Temperature Vary During the Day? . . . . . . . . . . . . . . . . . . 55
#2: Exploring a Quadratic Function Visually . . . . . . . . . . . . . . . . . . . . . . . . . 55
#3: Enhanced Projectile Trajectory Comparison Program . . . . . . . . . . . . . . . . 56
#4: Visualizing Your Expenses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
#5: Exploring the Relationship Between
the Fibonacci Sequence and the Golden Ratio . . . . . . . . . . . . . . . . . . . . . 59
3
Describing Data with Statistics 61
Finding the Mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Finding the Median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Finding the Mode and Creating a Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Finding the Most Common Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Finding the Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Creating a Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Measuring the Dispersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Finding the Range of a Set of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Finding the Variance and Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . . 72
Calculating the Correlation Between Two Data Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Calculating the Correlation Coefficient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
High School Grades and Performance on College Admission Tests . . . . . . . . . 78
Scatter Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Reading Data from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Reading Data from a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Reading Data from a CSV File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#1: Better Correlation Coefficient–Finding Program . . . . . . . . . . . . . . . . . . . . 89
#2: Statistics Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#3: Experiment with Other CSV Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#4: Finding the Percentile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
#5: Creating a Grouped Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4
Algebra and Symbolic Math with SymPy 93
Defining Symbols and Symbolic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Working with Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Factorizing and Expanding Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Pretty Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Substituting in Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Converting Strings to Mathematical Expressions . . . . . . . . . . . . . . . . . . . . . . 103
Solving Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Solving Quadratic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Solving for One Variable in Terms of Others . . . . . . . . . . . . . . . . . . . . . . . . 106
Solving a System of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Plotting Using SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Plotting Expressions Input by the User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Plotting Multiple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#1: Factor Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#2: Graphical Equation Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
#3: Summing a Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
#4: Solving Single-Variable Inequalities . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
x Contents in Detail
5
Playing with Sets and Probability 121
What’s a Set? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Set Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Subsets, Supersets, and Power Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Probability of Event A or Event B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Probability of Event A and Event B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Nonuniform Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
#1: Using Venn Diagrams to Visualize Relationships Between Sets . . . . . . . . . 140
#2: Law of Large Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
#3: How Many Tosses Before You Run Out of Money? . . . . . . . . . . . . . . . . . 144
#4: Shuffling a Deck of Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
#5: Estimating the Area of a Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
6
Drawing Geometric Shapes and Fractals 149
Drawing Geometric Shapes with Matplotlib’s Patches . . . . . . . . . . . . . . . . . . . . . . . . 150
Drawing a Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Creating Animated Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Animating a Projectile’s Trajectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Drawing Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Transformations of Points in a Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Drawing the Barnsley Fern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
#1: Packing Circles into a Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
#2: Drawing the Sierpiński Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
#3: Exploring Hénon’s Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
#4: Drawing the Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
7
Solving Calculus Problems 177
What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Domain and Range of a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
An Overview of Common Mathematical Functions . . . . . . . . . . . . . . . . . . . . 178
Assumptions in SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Finding the Limit of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Continuous Compound Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Instantaneous Rate of Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Finding the Derivative of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
A Derivative Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Calculating Partial Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Higher-Order Derivatives and Finding the Maxima and Minima . . . . . . . . . . . . . . . . . 188
Finding the Global Maximum Using Gradient Ascent . . . . . . . . . . . . . . . . . . . . . . . . 191
A Generic Program for Gradient Ascent . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
A Word of Warning About the Initial Value . . . . . . . . . . . . . . . . . . . . . . . . 196
The Role of the Step Size and Epsilon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Contents in Detail xi
Finding the Integrals of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Probability Density Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
What You Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Programming Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
#1: Verify the Continuity of a Function at a Point . . . . . . . . . . . . . . . . . . . . . 205
#2: Implement the Gradient Descent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
#3: Area Between Two Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
#4: Finding the Length of a Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Afterword 209
Things to Explore Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Project Euler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Python Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
A
Software Installation 213
Microsoft Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Updating SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Installing matplotlib-venn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Starting the Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
B
Overview of Python Topics 221
if __name__ == '__main__' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Dictionary Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Specifying Multiple Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
The else Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Reading Files in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Reading All the Lines at Once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Specifying the Filename as Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Handling Errors When Reading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Reusing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Index 237
xii Contents in Detail
Ac k n o w l ed g me n t s
I would like to thank everyone at No Starch Press for making this book
possible. From the first emails discussing the book idea with Bill Pollock
and Tyler Ortman, through the rest of the process, everyone there has
been an absolute pleasure to work with. Seph Kramer was amazing with his
technical insights and suggestions and Riley Hoffman was meticulous in
checking and re-checking that everything was correct. It is only fair to say
that without these two fine people, this book wouldn’t have been close to
what it is. Thanks to Jeremy Kun and Otis Chodosh for their insights and
making sure all the math made sense. I would also like to thank the copy-
editor, Julianne Jigour, for her thoroughness.
SymPy forms a core part of many chapters in this book and I would
like to thank everyone on the SymPy mailing list for answering my queries
patiently and reviewing my patches with promptness. I would also like to
thank the matplotlib community for answering and clearing up my doubts.
I would like to thank David Ash for lending me his Macbook, which
helped me when writing the software installation instructions.
I also must thank every writer and thinker who inspired me to write,
from humble web pages to my favorite books.
I n t r o duc t i o n
xvi Introduction
• Chapter 4, Algebra and Symbolic Math with SymPy, introduces sym-
bolic math using the SymPy library. It begins with the basics of repre-
senting and manipulating algebraic expressions before introducing
more complicated matters, such as solving equations.
• Chapter 5, Playing with Sets and Probability, discusses the representa-
tion of mathematical sets and moves on to basic discrete probability.
You’ll also learn to simulate uniform and nonuniform random events.
• Chapter 6, Drawing Geometric Shapes and Fractals, discusses using
matplotlib to draw geometric shapes and fractals and create animated
figures.
• Chapter 7, Solving Calculus Problems, discusses some of the math-
ematical functions available in the Python standard library and SymPy
and then introduces you to solving calculus problems.
• Appendix A, Software Installation, covers installation of Python 3,
matplotlib, and SymPy on Microsoft Windows, Linux, and Mac OS X.
• Appendix B, Overview of Python Topics, discusses several Python
topics that may be helpful for beginners.
Introduction xvii
1
W o r k i n g w i t h Numbe r s
>>> 1 + 2
3
>>> 1 + 3.5
4.5
>>> -1 + 2.5
1.5
>>> 100 – 45
55
>>> -1.1 + 5
3.9
>>> 3 * 2
6
>>> 3.5 * 1.5
5.25
>>> 3 / 2
1.5
>>> 4 / 2
2.0
As you can see, when you ask Python to perform a division operation,
it returns the fractional part of the number as well. If you want the result in
the form of an integer, with any decimal values removed, you should use the
floor division (//) operator:
>>> 3 // 2
1
2 Chapter 1
The floor division operator divides the first number by the second
number and then rounds down the result to the next lowest integer. This
becomes interesting when one of the numbers is negative. For example:
>>> -3 // 2
-2
The final result is the integer lower than the result of the division oper-
ation (-3/2 = -1.5, so the final result is -2).
On the other hand, if you want just the remainder, you should use the
modulo (%) operator:
>>> 9 % 2
1
You can calculate the power of numbers using the exponential (**)
operator. The examples below illustrate this:
>>> 2 ** 2
4
>>> 2 ** 10
1024
>>> 1 ** 10
1
We can also use the exponential symbol to calculate powers less than 1.
For example, the square root of a number n can be expressed as n1/2 and the
cube root as n1/3 :
>>> 8 ** (1/3)
2.0
>>> 5 + 5 * 5
30
>>> (5 + 5) * 5
50
u >>> a = 3
>>> a + 1
4
v >>> a = 5
>>> a + 1
6
>>> type(3)
<class 'int'>
>>> type(3.5)
<class 'float'>
>>> type(3.0)
<class 'float'>
4 Chapter 1
Here, you can see that Python classifies the number 3 as an integer
(type 'int') but classifies 3.0 as a floating point number (type 'float'). We
all know that 3 and 3.0 are mathematically equivalent, but in many situa-
tions, Python will treat these two numbers differently because they are two
different types.
Some of the programs we write in this chapter will work properly only
with an integer as an input. As we just saw, Python won’t recognize a num-
ber like 1.0 or 4.0 as an integer, so if we want to accept numbers like that
as valid input in these programs, we’ll have to convert them from floating
point numbers to integers. Luckily, there’s a function built in to Python that
does just that:
>>> int(3.8)
3
>>> int(3.0)
3
The function int() takes the input floating point number, gets rid of
anything that comes after the decimal point, and returns the resulting inte-
ger. The float() function works similarly to perform the reverse conversion:
>>> float(3)
3.0
float() takes the integer that was input and adds a decimal point to
turn it into a floating point number.
Now you know the basics of working with fractions in Python. Let’s
move on to a different kind of number.
Complex Numbers
The numbers we’ve seen so far are the so-called real numbers. Python also
supports complex numbers with the imaginary part identified by the letter j
or J (as opposed to the letter i used in mathematical notation). For example,
the complex number 2 + 3i would be written in Python as 2 + 3j:
>>> a = 2 + 3j
>>> type(a)
<class 'complex'>
As you can see, when we use the type() function on a complex number,
Python tells us that this is an object of type complex.
You can also define complex numbers using the complex() function:
>>> a = complex(2, 3)
>>> a
(2 + 3j)
Here we pass the real and imaginary parts of the complex number as
two arguments to the complex() function, and it returns a complex number.
You can add and subtract complex numbers in the same way as real
numbers:
>>> b = 3 + 3j
>>> a + b
(5 + 6j)
>>> a - b
(-1 + 0j)
6 Chapter 1
Multiplication and division of complex numbers are also carried out
similarly:
>>> a * b
(-3 + 15j)
>>> a / b
(0.8333333333333334 + 0.16666666666666666j)
The modulus (%) and the floor division (//) operations are not valid for
complex numbers.
The real and imaginary parts of a complex number can be retrieved
using its real and imag attributes, as follows:
>>> z = 2 + 3j
>>> z.real
2.0
>>> z.imag
3.0
The conjugate of a complex number has the same real part but an imagi-
nary part with an equal magnitude and an opposite sign. It can be obtained
using the conjugate() method:
>>> z.conjugate()
(2 - 3j)
Both the real and imaginary parts are floating point numbers. Using the
real and imaginary parts, you can then calculate the magnitude of a complex
number with the following formula, where x and y are the real and imaginary
parts of the number, respectively: . In Python, this would look like
the following:
>>> abs(z)
3.605551275463989
The standard library’s cmath module (cmath for complex math) provides
access to a number of other specialized functions to work with complex
numbers.
u >>> a = input()
v 1
At u, we call the input() function, which waits for you to type something,
as shown at v, and press enter. The input provided is stored in a:
>>> a
w '1'
>>> a = '1'
>>> int(a) + 1
2
>>> float(a) + 1
2.0
These are the same int() and float() functions we saw earlier, but this
time instead of converting the input from one kind of number to another,
they take a string as input ('1') and return a number (2 or 2.0). It’s impor-
tant to note, however, that the int() function cannot convert a string con-
taining a floating point decimal into an integer. If you take a string that has
a floating point number (like '2.5' or even '2.0') and input that string into
the int() function, you’ll get an error message:
>>> int('2.0')
Traceback (most recent call last):
8 Chapter 1
File "<pyshell#26>", line 1, in <module>
int('2.0')
ValueError: invalid literal for int() with base 10: '2.0'
>>> a = float(input())
3/4
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
a=float(input())
ValueError: could not convert string to float: '3/4'
>>> try:
a = float(input('Enter a number: '))
except ValueError:
print('You entered an invalid number')
The user will now see the message hinting to enter an integer as input:
Input an integer: 1
In many programs in this book, we’ll ask the user to enter a number
as input, so we’ll have to make sure we take care of conversion before we
attempt to perform any operations on these numbers. You can combine the
input and conversion in a single statement, as follows:
>>> a = int(input())
1
>>> a + 1
2
This works great if the user inputs an integer. But as we saw earlier, if
the input is a floating point number (even one that’s equivalent to an inte-
ger, like 1.0), this will produce an error:
>>> a = int(input())
1.0
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
a=int(input())
ValueError: invalid literal for int() with base 10: '1.0'
In order to avoid this error, we could set up a ValueError catch like the
one we saw earlier for fractions. That way the program would catch float-
ing point numbers, which won’t work in a program meant for integers.
However, it would also flag numbers like 1.0 and 2.0, which Python sees as
floating point numbers but that are equivalent to integers and would work
just fine if they were entered as the right Python type.
To get around all this, we will use the is_integer() method to filter out
any numbers with a significant digit after the decimal point. (This method
is only defined for float type numbers in Python; it won’t work with num-
bers that are already entered in integer form.)
Here’s an example:
>>> 1.1.is_integer()
False
10 Chapter 1
Exploring the Variety of Random
Documents with Different Content
negoziazioni di sciogliere la lega che gli aveva tolto il Milanese, e di
procurarsi in Italia nuovi alleati.
La lega trovavasi di già talmente divisa da opposti interessi, che in
certo modo Lodovico XII era padrone di scegliere a suo piacimento i
suoi nuovi alleati. Ferdinando, che in ogni sua azione coprivasi
sempre ipocritamente col manto della religione, gli aveva mandati in
Francia due monaci per trattare con lui, proponendogli o una pace
generale, o una parziale alleanza; ma perchè la prima proposizione
di Ferdinando richiedeva che Lodovico XII abbandonasse la Navarra,
questi rispose che l'onor suo voleva che soccorresse un re che si era
gettato nel pericolo soltanto per attaccamento verso di lui [302].
Dall'altro canto la regina Anna di Bretagna aveva fatto fare delle
aperture di negoziazione al cardinale di Gurck, che erano state
accettate; e Massimiliano aveva in cambio fatto proporre a Lodovico
di unire in matrimonio il suo piccolo nipote, l'arciduca Carlo, colla
seconda figlia del re, purchè questa gli portasse in dote i diritti della
Francia sul Milanese e sui regno di Napoli. Chiedeva inoltre che la
giovane principessa si mandasse immediatamente alla corte
imperiale per essere colà educata fino all'epoca del matrimonio, e
che il re secondasse Massimiliano nel suo progetto di ruinare affatto i
Veneziani [303]. La regina Anna non volle acconsentire alla
separazione di sua figlia, ed i consiglieri di Lodovico XII lo dissuasero
dal contrarre alleanza con un imperatore, che non era mai di buona
fede nelle sue promesse, e che, quand'anche lo fosse, e
quand'anche avesse perdonate alla Francia le diciassette offese che
diceva avere da questa ricevute, si poneva sempre nell'impossibilità
di soddisfare ai suoi impegni [304].
Lodovico XII non ignorava le funeste conseguenze della sua
malintelligenza cogli Svizzeri, ed ardentemente desiderava di
riconciliarsi, ma questa negoziazione presentava maggiori difficoltà
che non le altre. Sapeva essere stato sottoscritto un trattato tra gli
ambasciatori svizzeri e Massimiliano Sforza, in forza del quale la
confederazione prendeva sotto la sua protezione la casa Sforza,
permettendole di levare per la difesa del Milanese quante truppe le
piacesse; ed il duca prometteva cento cinquanta mila ducati nell'atto
di entrare in possesso de' suoi stati, e per venticinque anni quaranta
mila ducati all'anno. Lodovico caldamente desiderava di fare in modo
che la dieta non ratificasse questo trattato, lo che non era fin allora
accaduto. Soltanto per ottenere che i suoi ambasciatori potessero
presentarsi a questa dieta, cedette agli Svizzeri le fortezze di Lugano
e di Locarno: ed a tale condizione il signore de la Tremouille ebbe la
licenza di portarsi a Lucerna, ov'era adunata l'assemblea. Vi si recò
nello stesso tempo ancora Gian Giacopo Trivulzio, sotto pretesto di
trattarvi alcuni suoi particolari interessi; ma subito gli Svizzeri gli
proibirono di comunicare con la Tremouille, ed alla presenza dell'uno
e dell'altro ratificarono la convenzione conchiusa collo Sforza, e
ricusarono al re di Francia ogni leva di soldati, ed ogni altra
domanda [305].
Nello stesso tempo Lodovico XII avea preso a negoziare coi
Veneziani col mezzo del Trivulzio e di Andrea Gritti, che trovavasi
tuttavia prigioniere dopo la battaglia di Ghiara d'Adda, e che il re
aveva fatto venire alla sua corte. Ma sebbene queste pratiche si
continuassero segretamente, Massimiliano n'ebbe qualche sentore, e
per romperle si mostrò disposto a recedere dalle sue pretese,
rinunciando alla restituzione di Vicenza. Risposero i Veneziani al
cardinale di Gurck, che non tratterebbero, se non a condizione che
fosse loro restituita Verona, senza la quale città il loro territorio si
trovava diviso in due parti; soltanto offrirono in compenso
all'imperatore d'accrescere il tributo loro domandato. Il che non
avendo potuto essi ottenere, sottoscrissero col segretario del
Trivulzio, mandato segretamente a Venezia, un trattato d'alleanza
colla Francia. Servì di base a questo nuovo trattato quello del 1499
tra le due medesime potenze, in forza del quale davansi ai Veneziani
Cremona e la Ghiara d'Adda [306], e a Lodovico XII tutto il restante
del ducato di Milano.
Il segretario del Trivulzio, che aveva redatto questo trattato per la
Francia, aveva fatta l'espressa riserva, che terrebbesi come non
avvenuto, qualunque volta non fosse dal re ratificato entro un
determinato tempo. Perciò fin allora nulla era conchiuso, e ciascuno
tirava avanti nelle sue contraddittorie negoziazioni. Lodovico XII
aveva mandato a Massimiliano il signore d'Asparoth, fratello di
Lautrec, per continuare le negoziazioni relative alle proposizioni del
matrimonio di madama Renata di Francia. Dall'altro canto
Ferdinando confortava caldamente Massimiliano a cedere Verona ai
Veneziani e ad accettare invece dugento cinquanta mila ducati
d'investitura, e cinquanta mila di annuo censo. Gli proponeva di
adoperare questo danaro per portare la guerra in Borgogna, e
prendersi larghi compensi in Francia alle conquiste che abbandonava
in Italia. Egli aveva impegnato il cardinale di Gurck, ch'era
perfettamente entrato nelle sue viste, a recarsi in Germania per
appoggiarle, e lo aveva fatto accompagnare da don Pedro di Urrea,
suo ambasciatore, e dal conte di Cariati, suo ministro presso la
repubblica di Venezia. Per dare più largo tempo a tutte queste
negoziazioni, si stipulò una tregua a tutto marzo tra i Tedeschi ed i
Veneziani [307].
Il più attivo in queste così complicate negoziazioni era però sempre
Giulio II. Stava con impazienza aspettando la buona stagione per
attaccare Ferrara, il di cui duca, abbandonato da tutti i suoi alleati,
non poteva opporgli lunga resistenza. Aveva segretamente pel
prezzo di trenta mila ducati acquistati da Massimiliano i diritti
dell'impero sopra Siena, e contava di farne un dono a suo nipote, il
duca d'Urbino: mercè un'altra somma di quaranta mila ducati
Massimiliano doveva pure consegnargli Modena in pegno. Egli
minacciava i Lucchesi, ai quali voleva togliere la Garfagnana, che
avevano conquistata sopra Alfonso d'Este in tempo delle sue
calamità. Era scontento dei Medici, che trovava più attaccati alla
corte di Spagna che a lui, e meditava di mutare nuovamente la
costituzione di Firenze. Aveva tolta al cardinale di Sion la legazione di
Milano, e lo aveva richiamato a Roma, per gastigarlo delle
concussioni colle quali questo prelato erasi formata in Lombardia
un'entrata di trenta mila ducati. Apparecchiavasi a scacciare da
Perugia Giovanni Baglioni, per sostituirgli Carlo Baglioni, e a far
deporre Giano Fregoso, doge di Genova, per far eleggere in sua vece
Ottaviano Fregoso. I soli Svizzeri continuavano a parergli degni della
sua stima e dell'amor suo. Col loro soccorso egli sperava di terminare
di cacciare i barbari d'Italia, secondo la favorita sua espressione, e di
disfarsi un giorno degli Spagnuoli; ed il cardinale Grimani avendo
detto in sua presenza che il regno di Napoli rimaneva sempre in
mano degli stranieri, Giulio II, battendo sul suolo col suo bastone,
disse, che se il cielo gli dava vita non tarderebbe a liberare anche i
Napolitani dal giogo che gli opprimeva [308]. Finalmente
nell'implacabile sua collera contro la Francia trasferiva con una bolla
al re d'Inghilterra il titolo di Cristianissimo, privava Lodovico del
regno di Francia, e lo accordava al primo occupante [309].
Tutti questi progetti fermentavano nello stesso tempo nel capo di
Giulio II, quando una leggiere ma ostinata febbre, cui ben tosto
s'aggiunse la dissenteria, gli fece sentire che poco gli rimaneva a
vivere. Chiamò presso di sè i cardinali in concistoro, e fece loro
confermare la bolla contro la simonia, ch'egli aveva pubblicata dopo
la sua prima malattia. Fece loro dichiarare, che i cardinali scismatici
sarebbero esclusi dal conclave, al quale, e non già al concilio
adunato, lasciò l'elezione del suo successore; persuase di nuovo i
cardinali a confermare il vicariato di Pesaro a suo nipote, il duca
d'Urbino, in vista che questa era la sola grazia ch'egli accordava alla
propria famiglia. Infatti non si presentò nella storia una sola
occasione di parlare di Madonna Felicia, sua figlia, maritata a Gian
Giordano Orsini. Egli mai non le aveva accordato verun favore; ed un
giorno ch'ella caldamente gli chiedeva il cappello di cardinale per
Guido di Montefalco, suo fratello per parte di madre, glielo rifiutò
aspramente, dichiarando che non erane degno. Giulio II conservò
fino all'ultimo istante la stessa fermezza, la stessa costanza, tutto il
vigore della sua anima e tutto il suo discernimento. Ricevette i
sacramenti della Chiesa, e morì dopo più giorni di patimenti nella
notte del 21 febbrajo nel 1513 [310][311].
CAPITOLO CXI.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com