Doing Math with Python
{2}————————————————
{3}————————————————
D o i n g M a t h with Python
U s e P r o g r a m m i n g t o Explore Al g e b r a , S t a t i s t i c s , Calculus, and More!
by Amit Saha

San Francisco
{4}————————————————
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
Publisher: William Pollock Production Editor: Riley Hoffman Cover Illustration: Josh Ellingson Interior Design: Octopod Studios
Developmental Editors: Seph Kramer and Tyler Ortman
Technical Reviewer: Jeremy Kun Copyeditor: Julianne Jigour Compositor: Riley Hoffman Proofreader: Paula L. Fleming
For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103 phone: 415.863.9900; info@nostarch.com www.nostarch.com
Library of Congress Cataloging-in-Publication Data
Saha, Amit, author.
Doing math with Python : use programming to explore algebra, statistics, calculus, and more! / by Amit Saha.
pages cm
Summary: “Uses the Python programming language as a tool to explore high school-level mathematics like statistics, geometry, probability, and calculus by writing programs to find derivatives, solve equations graphically, manipulate algebraic expressions, and examine projectile motion. Covers programming concepts including using functions, handling user input, and reading and manipulating data”– Provided by publisher.
Includes index.
ISBN 978-1-59327-640-9 – ISBN 1-59327-640-0
- Mathematics–Study and teaching–Data processing. 2. Python (Computer program language) 3. Computer programming. I. Title.
QA20.C65S24 2015 510.285‘5133–dc23
2015009186
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.
{5}————————————————

{6}————————————————
{7}————————————————
Bri e f Cont e n t s
| Acknowledgments | xii |
|---|---|
| Introduction | xv |
| Chapter 1: Working with Numbers | 1 |
| Chapter 2: Visualizing Data with Graphs | 27 |
| Chapter 3: Describing Data with Statistics | 61 |
| Chapter 4: Algebra and Symbolic Math with SymPy | 93 |
| Chapter 5: Playing with Sets and Probability | 121 |
| Chapter 6: Drawing Geometric Shapes and Fractals | 149 |
| Chapter 7: Solving Calculus Problems | 177 |
| Afterword | 209 |
| Appendix A: Software Installation | 213 |
| Appendix B: Overview of Python Topics | 221 |
| Index | 237 |
{8}————————————————
{9}————————————————
Cont e n t s in De tail
| ACKNOWLEDGMENTS | xiii |
|---|---|
| INTRODUCTION | xv |
| Who Should Read This Book | xv |
| What’s in This Book? | xv |
| Scripts, Solutions, and Hints | xvi |
| 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 |
| 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 |
| 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 |
{10}————————————————
{11}————————————————
{12}————————————————
{13}————————————————
Acknowl edg 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 copyeditor, 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.
{14}————————————————
{15}————————————————