Table of contents : Cover......Page 1 Title Page......Page 5 Preface......Page 7 Contents......Page 8 Changes to the First Edition......Page 10 Acknowledgments......Page 11 Contents......Page 13 List of Exercises......Page 25 1.1 The First Programming Encounter: A Formula......Page 35 1.1.2 About Programs and Programming......Page 36 1.1.3 Tools for Writing Programs......Page 37 1.1.4 Using Idle to Write the Program......Page 38 Warning About Typing Program Text......Page 40 1.1.5 How to Run the Program......Page 41 1.1.7 Using Variables......Page 42 1.1.8 Names of Variables......Page 43 1.1.10 Comments......Page 44 Printf Syntax......Page 45 Format String Syntax......Page 47 1.2 Computer Science Glossary......Page 48 Straightforward Coding of the Formula......Page 53 1.3.2 Objects in Python......Page 54 1.3.3 Avoiding Integer Division......Page 55 1.3.4 Arithmetic Operators and Precedence......Page 56 Problem......Page 57 Two Ways of Importing a Module......Page 58 1.4.2 Example: Using More Mathematical Functions......Page 59 1.4.3 A First Glimpse of Round-Off Errors......Page 60 1.5.1 Using the Python Shell......Page 61 1.5.2 Type Conversion......Page 62 1.5.3 IPython......Page 63 Quick Recovery of Previous Output......Page 64 Remark......Page 65 1.6 Complex Numbers......Page 66 1.6.2 Complex Functions in Python......Page 67 1.6.3 Unified Treatment of Complex and Real Functions......Page 68 Program Files......Page 69 Object Types......Page 70 Common Mathematical Functions......Page 71 Terminology......Page 72 Solution......Page 73 1.7.3 About Typesetting Conventions in This Book......Page 74 What Does It Mean to Solve an Exercise?......Page 75 2.1.1 A Naive Solution......Page 83 2.1.2 While Loops......Page 84 2.1.3 Boolean Expressions......Page 86 2.1.4 Loop Implementation of a Sum......Page 88 2.2.1 Basic List Operations......Page 89 The Nature of For Loops......Page 92 Making the Table......Page 93 2.3.2 The Range Construction......Page 94 2.3.3 For Loops with List Indices......Page 95 2.3.5 List Comprehension......Page 97 2.4 Nested Lists......Page 98 2.4.1 A Table as a List of Rows or Columns......Page 99 Modules for Pretty Print of Objects......Page 100 2.4.3 Extracting Sublists......Page 101 2.4.4 Traversing Nested Lists......Page 103 2.5 Tuples......Page 105 While Loops......Page 106 Nested Lists......Page 107 For Loops......Page 108 Problem......Page 109 Solution......Page 110 2.6.3 How to Find More Python Information......Page 112 2.7 Exercises......Page 113 3.1.1 Functions of One Variable......Page 121 3.1.2 Local and Global Variables......Page 123 3.1.3 Multiple Arguments......Page 125 3.1.4 Multiple Return Values......Page 127 3.1.5 Functions with No Return Values......Page 129 3.1.6 Keyword Arguments......Page 130 Example: Function with Default Parameters......Page 131 Example: Computing a Sum with Default Tolerance......Page 132 3.1.7 Doc Strings......Page 133 3.1.9 Functions as Arguments to Functions......Page 134 The Behavior of the Numerical Derivative as h → 0......Page 135 3.1.10 The Main Program......Page 136 3.1.11 Lambda Functions......Page 137 3.2.1 If-Else Blocks......Page 138 3.2.2 Inline If Tests......Page 140 List Iteration......Page 141 Program Flow......Page 142 While Loops......Page 144 List Comprehensions......Page 145 Using Python's Library......Page 146 Generating Random DNA Strings......Page 147 Measuring CPU Time......Page 148 Keyword Arguments......Page 149 Problem......Page 150 Solution......Page 151 3.5 Exercises......Page 154 4 Input Data and Error Handling......Page 171 4.1.1 Reading Keyboard Input......Page 172 4.1.2 The Magic “eval” Function......Page 173 4.1.3 The Magic “exec” Function......Page 177 4.1.4 Turning String Expressions into Functions......Page 178 4.2.1 Providing Input on the Command Line......Page 179 4.2.2 A Variable Number of Command-Line Arguments......Page 180 4.2.3 More on Command-Line Arguments......Page 181 4.2.4 Option-Value Pairs on the Command Line......Page 182 4.3 Handling Errors......Page 186 4.3.1 Exception Handling......Page 187 Testing for a Specific Exception......Page 188 Examples on Exception Types......Page 189 Example......Page 190 4.4 A Glimpse of Graphical User Interfaces......Page 192 4.5.1 Example: Interest on Bank Deposits......Page 195 4.5.2 Collecting Functions in a Module File......Page 196 Test Block......Page 197 Flexible Test Blocks......Page 198 4.5.3 Using Modules......Page 201 Question and Answer Input......Page 203 Generating Code on the Fly......Page 204 Handling Exceptions......Page 205 Problem......Page 206 Solution......Page 207 Making a Function......Page 210 Making a Module......Page 211 A Flexible Program for Solving f(x) = 0......Page 212 4.7 Exercises......Page 214 5 Array Computing and Curve Plotting......Page 221 5.1.1 The Vector Concept......Page 222 5.1.2 Mathematical Operations on Vectors......Page 223 5.1.3 Vector Arithmetics and Vector Functions......Page 225 5.2.1 Using Lists for Collecting Function Data......Page 227 5.2.2 Basics of Numerical Python Arrays......Page 228 5.2.3 Computing Coordinates and Function Values......Page 229 5.2.4 Vectorization......Page 230 5.3.1 Matplotlib; Pylab......Page 232 Decorating the Plot......Page 233 Plotting Multiple Curves......Page 234 Placing Several Plots in One Figure......Page 235 5.3.2 Matplotlib; Pyplot......Page 236 Importing SciTools and Easyviz......Page 238 Decorating the Plot......Page 240 Plotting Multiple Curves......Page 241 Placing Several Plots in One Figure......Page 242 Example......Page 243 Animation in Matplotlib......Page 245 Remarks on Filenames......Page 246 Movie Formats......Page 247 5.3.5 Curves in Pure Text......Page 248 5.4 Plotting Difficulties......Page 249 Example: The Heaviside Function......Page 250 Example: A Hat Function......Page 251 5.4.2 Rapidly Varying Functions......Page 252 5.5 More Advanced Vectorization of Functions......Page 253 5.5.1 Vectorizing StringFunction Objects......Page 254 Loop......Page 255 Manual Vectorization......Page 256 5.5.3 Vectorization of a Hat Function......Page 258 5.6.1 Copying Arrays......Page 260 5.6.2 In-Place Arithmetics......Page 261 5.6.4 Generalized Indexing......Page 262 Example: Vectorizing a Constant Function......Page 263 5.6.7 Shape Manipulation......Page 264 5.7.1 Matrices and Arrays......Page 265 5.7.2 Two-Dimensional Numerical Python Arrays......Page 266 5.7.4 Two-Dimensional Arrays and Functions of Two Variables......Page 269 5.7.5 Matrix Objects......Page 270 5.8.1 Chapter Topics......Page 271 Making Movies......Page 272 Solution......Page 273 Scaling......Page 275 5.9 Exercises......Page 277 6.1 Reading Data from File......Page 291 For Loop over Lines......Page 292 Reading a File into a String......Page 294 6.1.2 Reading a Mixture of Text and Numbers......Page 295 6.1.3 What Is a File, Really?......Page 296 Pure Text Files......Page 297 Image Files......Page 298 Remarks......Page 299 6.2.1 Making Dictionaries......Page 300 6.2.2 Dictionary Operations......Page 301 Remark......Page 302 6.2.3 Example: Polynomials as Dictionaries......Page 303 Dictionaries with Default Values......Page 305 Ordered Dictionaries......Page 306 Problem......Page 307 Algorithm......Page 308 Implementation......Page 309 Dissection......Page 310 Problem......Page 312 Solution......Page 313 6.3.1 Common Operations on Strings......Page 316 Substitution......Page 317 Strings Are Constant......Page 318 Joining Strings......Page 319 Solution......Page 320 Problem......Page 322 Solution 1: Substring Extraction......Page 323 Solution 3: String Split......Page 324 6.4.1 About Web Pages......Page 325 6.4.2 How to Access Web Pages in Programs......Page 326 6.4.3 Example: Reading Pure Text Files......Page 327 6.4.4 Example: Extracting Data from HTML......Page 329 Solution......Page 330 6.5.2 Standard Input and Output as File Objects......Page 332 Redirecting Standard Input, Output, and Error......Page 333 6.5.3 Reading and Writing Spreadsheet Files......Page 334 Reading CSV Files......Page 335 Remark......Page 337 Representing Number Cells with Numerical Python Arrays......Page 338 6.6.1 Computing Frequencies......Page 339 Separate Frequency Lists......Page 340 Nested List......Page 341 Numerical Python Array......Page 342 Dictionary of Lists......Page 343 Remark......Page 344 Using Arrays and Vectorization......Page 345 6.6.2 Analyzing the Frequency Matrix......Page 346 Dict of Dicts Frequency Matrix......Page 347 6.6.3 Finding Base Frequencies......Page 349 6.6.4 Translating Genes into Proteins......Page 351 6.6.5 Some Humans Can Drink Milk, While Others Cannot......Page 356 File Operations......Page 357 Dictionaries......Page 358 Problem......Page 359 Solution......Page 360 6.8 Exercises......Page 363 7 Introduction to Classes......Page 375 Problem......Page 376 A Bad Solution: Global Variables......Page 377 7.1.2 Representing a Function as a Class......Page 378 Implementation......Page 379 Usage and Dissection......Page 380 The self Variable......Page 381 Remark......Page 382 Doc Strings......Page 383 7.1.3 Another Function Class Example......Page 384 7.1.4 Alternative Function Class Implementations......Page 385 7.1.5 Making Classes Without the Class Construct......Page 387 Second Remark......Page 389 7.2.1 Bank Accounts......Page 390 7.2.2 Phone Book......Page 392 7.2.3 A Circle......Page 393 7.3 Special Methods......Page 394 Problem......Page 395 Solution......Page 396 Application: Newton's Method......Page 397 7.3.3 Example: Automagic Integration......Page 398 A Simple Implementation......Page 399 7.3.4 Turning an Instance into a String......Page 400 7.3.5 Example: Phone Book with Special Methods......Page 401 Remark......Page 402 Implementation......Page 403 Usage......Page 405 Pretty Print of Polynomials......Page 406 7.3.8 Arithmetic Operations and Other Special Methods......Page 407 7.3.9 Special Methods for String Conversion......Page 408 7.4 Example: Class for Vectors in the Plane......Page 409 7.4.2 Implementation......Page 410 7.4.3 Usage......Page 412 7.5 Example: Class for Complex Numbers......Page 413 7.5.1 Implementation......Page 414 7.5.2 Illegal Operations......Page 415 7.5.3 Mixing Complex and Real Numbers......Page 416 Computer Science Discussion......Page 417 7.5.4 Special Methods for “Right” Operands......Page 418 Remark......Page 419 7.5.5 Inspecting Instances......Page 420 7.6 Static Methods and Attributes......Page 421 Classes......Page 422 7.7.2 Example: Interval Arithmetics......Page 423 Solution......Page 425 7.8 Exercises......Page 429 8 Random Numbers and Simple Games......Page 447 8.1.1 The Seed......Page 448 8.1.2 Uniformly Distributed Random Numbers......Page 449 8.1.3 Visualizing the Distribution......Page 450 Warning......Page 451 8.1.5 Computing the Mean and Standard Deviation......Page 452 8.1.6 The Gaussian or Normal Distribution......Page 453 8.2 Drawing Integers......Page 454 8.2.1 Random Integer Functions......Page 455 8.2.3 Drawing a Random Element from a List......Page 456 8.2.4 Example: Drawing Cards from a Deck......Page 457 8.2.5 Example: Class Implementation of a Deck......Page 459 8.3.1 Principles of Monte Carlo Simulation......Page 462 Straightforward Solution......Page 463 A Game......Page 464 Decide If a Game Is Fair......Page 465 8.3.3 Example: Drawing Balls from a Hat......Page 466 Vectorized Version......Page 468 A Markov Chain Mutation Model......Page 470 8.3.5 Example: Policies for Limiting Population Growth......Page 473 The Implementation......Page 476 The Implementation......Page 477 A Class Version......Page 478 8.5.1 Standard Monte Carlo Integration......Page 480 8.5.2 Area Computing by Throwing Random Points......Page 482 8.6 Random Walk in One Space Dimension......Page 484 8.6.1 Basic Implementation......Page 485 8.6.3 Random Walk as a Difference Equation......Page 486 8.6.4 Computing Statistics of the Particle Positions......Page 487 8.6.5 Vectorized Implementation......Page 488 8.7.1 Basic Implementation......Page 490 8.7.2 Vectorized Implementation......Page 491 Typical Probability Computation......Page 493 Problem......Page 494 Solution......Page 495 8.9 Exercises......Page 500 9.1 Inheritance and Class Hierarchies......Page 517 9.1.1 A Class for Straight Lines......Page 518 9.1.3 A Class for Parabolas Using Inheritance......Page 519 9.1.4 Checking the Class Type......Page 521 9.1.5 Attribute Versus Inheritance......Page 522 9.1.6 Extending Versus Restricting Functionality......Page 523 9.1.7 Superclass for Defining an Interface......Page 524 9.2 Class Hierarchy for Numerical Differentiation......Page 526 9.2.1 Classes for Differentiation......Page 527 Computer Science Remark......Page 529 9.2.2 A Flexible Main Program......Page 530 9.2.3 Extensions......Page 531 Application......Page 532 9.2.4 Alternative Implementation via Functions......Page 534 9.2.5 Alternative Implementation via Functional Programming......Page 535 9.2.6 Alternative Implementation via a Single Class......Page 536 Remark......Page 537 9.3.1 Numerical Integration Methods......Page 538 9.3.2 Classes for Integration......Page 539 9.3.3 Using the Class Hierarchy......Page 543 9.3.4 About Object-Oriented Programming......Page 545 9.4 Class Hierarchy for Making Drawings......Page 547 Basic Drawing......Page 548 Groups of Objects......Page 549 The Figure Composition as an Object Hierarchy......Page 550 Animation: Translating the Vehicle......Page 553 Animation: Rolling the Wheels......Page 555 Simple Geometric Objects......Page 557 Class Curve......Page 559 Compound Geometric Objects......Page 560 Basic Principles of Recursion......Page 562 Explaining Recursion......Page 563 Scaling......Page 565 Translation......Page 566 Rotation......Page 567 9.5.2 Class for Genes......Page 568 Basic Features of class Gene......Page 569 Flexible Constructor......Page 570 Other Methods......Page 571 9.5.3 Subclasses......Page 573 Acknowledgments......Page 574 Subclassing in General......Page 575 Problem......Page 576 Solution......Page 577 Reading from File......Page 578 Reading from the Command Line......Page 579 More Flexibility in the Superclass......Page 580 Demonstrating the Tool......Page 581 9.7 Exercises......Page 582 A Sequences and Difference Equations......Page 591 A.1 Mathematical Models Based on Difference Equations......Page 592 A.1.1 Interest Rates......Page 593 A.1.2 The Factorial as a Difference Equation......Page 595 A.1.3 Fibonacci Numbers......Page 596 A.1.4 Growth of a Population......Page 597 A.1.5 Logistic Growth......Page 598 A.1.6 Payback of a Loan......Page 600 A.1.7 The Integral as a Difference Equation......Page 601 A.1.8 Taylor Series as a Difference Equation......Page 603 A.1.10 Newton's Method......Page 605 A.1.11 The Inverse of a Function......Page 609 A.2 Programming with Sound......Page 611 A.2.1 Writing Sound to File......Page 612 A.2.2 Reading Sound from File......Page 613 Problem......Page 614 Solution......Page 615 A.3 Exercises......Page 617 B.1 Discrete Functions......Page 627 B.1.1 The Sine Function......Page 628 B.1.3 Evaluating the Approximation......Page 630 B.1.4 Generalization......Page 631 B.2 Differentiation Becomes Finite Differences......Page 633 B.2.2 Differences on a Mesh......Page 634 B.2.3 Generalization......Page 636 B.3 Integration Becomes Summation......Page 637 B.3.1 Dividing into Subintervals......Page 638 B.3.2 Integration on Subintervals......Page 639 B.3.3 Adding the Subintervals......Page 640 B.3.4 Generalization......Page 641 B.4.2 Approximating the Exponential Function......Page 643 B.4.3 More Accurate Expansions......Page 644 B.4.4 Accuracy of the Approximation......Page 646 B.4.5 Derivatives Revisited......Page 648 B.4.6 More Accurate Difference Approximations......Page 649 B.4.7 Second-Order Derivatives......Page 651 B.5 Exercises......Page 653 C Introduction to Differential Equations......Page 659 C.1 The Simplest Case......Page 660 C.2 Exponential Growth......Page 662 Numerical Solution......Page 664 C.3 Logistic Growth......Page 667 C.4 A Simple Pendulum......Page 668 C.5 A Model for the Spread of a Disease......Page 671 C.6 Exercises......Page 673 D.1.1 The Physical Problem......Page 675 The Key Quantities......Page 677 D.1.3 Derivation of the Mathematical Model......Page 678 D.1.4 Derivation of the Algorithm......Page 680 D.2.1 Implementation......Page 682 D.2.2 Callback Functionality......Page 685 D.2.3 Making a Module......Page 686 D.2.4 Verification......Page 687 D.3.1 Simultaneous Computation and Plotting......Page 689 Fixing Axes......Page 690 D.3.3 Remark on Choosing Δt......Page 692 D.3.4 Comparing Several Quantities in Subplots......Page 693 D.3.5 Comparing Approximate and Exact Solutions......Page 694 D.3.6 Evolution of the Error as Δt Decreases......Page 695 D.4 Exercises......Page 699 E Programming of Differential Equations......Page 701 E.1.1 Examples on Right-Hand-Side Functions......Page 702 E.1.2 The Forward Euler Scheme......Page 704 E.1.4 Verifying the Implementation......Page 705 E.1.5 From Discrete to Continuous Solution......Page 706 E.1.6 Switching Numerical Method......Page 707 Class Wrapping of a Function......Page 708 A More Flexible Class......Page 709 E.2 Systems of Ordinary Differential Equations......Page 711 E.2.1 Mathematical Problem......Page 712 E.2.2 Example of a System of ODEs......Page 714 Function Implementation......Page 715 Class Implementation......Page 716 E.2.4 Numerical Methods......Page 718 E.2.5 The ODE Solver Class Hierarchy......Page 719 The Superclass......Page 720 Remark......Page 721 E.2.6 The Backward Euler Method......Page 722 E.2.7 Application 1: u' = -u......Page 725 Basic Problem and Solver Classes......Page 727 Computing an Appropriate Δt......Page 729 Dealing with Time-Dependent Coefficients......Page 731 Reading Input......Page 732 E.2.9 Application 3: An Oscillating System......Page 734 E.2.10 Application 4: The Trajectory of a Ball......Page 736 E.2.11 Further Developments of ODESolver......Page 738 E.3 Exercises......Page 739 F.1 Using a Debugger......Page 769 F.2.1 A Recipe for Program Writing and Debugging......Page 772 Problem......Page 774 Solution......Page 775 Refining the User Interface......Page 784 G Migrating Python to Compiled Code......Page 787 G.1.2 A Scalar Python Implementation......Page 788 G.1.3 A Vectorized Python Implementation......Page 789 G.2.1 A Plain Cython Implementation......Page 791 G.2.2 A Better Cython Implementation......Page 793 G.3.1 Writing a C Program......Page 795 G.3.2 Migrating Loops to C Code via F2PY......Page 796 G.3.3 Migrating Loops to C Code via Cython......Page 798 G.3.4 Comparing Efficiency......Page 799 H.1.2 Executing Python Programs on Unix......Page 801 H.1.3 Executing Python Programs on Windows......Page 803 Gnuplot Plots on Windows......Page 804 H.2 Integer and Float Division......Page 805 H.3 Visualizing a Program with Lumpy......Page 806 H.4 Doing Operating System Tasks in Python......Page 808 H.5 Variable Number of Function Arguments......Page 810 Example......Page 811 Example......Page 813 H.6.1 Making Time Measurements......Page 815 Hardware Information......Page 816 H.6.2 Profiling Python Programs......Page 817 References......Page 819 Index......Page 821