Math Adventures with Python An Illustrated Guide to Exploring Math with Code (Peter Farrell) (Z-Library)

Author: Peter Farrell

商业

Learn math by getting creative with code! Use the Python programming language to transform learning high school-level math topics like algebra, geometry, trigonometry, and calculus! Math Adventures with Python will show you how to harness the power of programming to keep math relevant and fun. With the aid of the Python programming language, you'll learn how to visualize solutions to a range of math problems as you use code to explore key mathematical concepts like algebra, trigonometry, matrices, and cellular automata. Once you've learned the programming basics like loops and variables, you'll write your own programs to solve equations quickly, make cool things like an interactive rainbow grid, and automate tedious tasks like factoring numbers and finding square roots. You'll learn how to write functions to draw and manipulate shapes, create oscillating sine waves, and solve equations graphically. You'll also learn how to: - Draw and transform 2D and 3D graphics with matrices - Make colorful designs like the Mandelbrot and Julia sets with complex numbers - Use recursion to create fractals like the Koch snowflake and the Sierpinski triangle - Generate virtual sheep that graze on grass and multiply autonomously - Crack secret codes using genetic algorithms As you work through the book's numerous examples and increasingly challenging exercises, you'll code your own solutions, create beautiful visualizations, and see just how much more fun math can be!

📄 File Format: PDF
💾 File Size: 17.4 MB
14
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
MATH ADVENTURES WITH PYTHON AN ILLUSTRATED GUIDE TO EXPLORING MATH WITH CODE BY PETER FARRELL San Francisco Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
📄 Page 3
MATH ADVENTURES WITH PYTHON. Copyright © 2019 by Peter Farrell. 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. ISBN­10: 1­59327­867­5 ISBN­13: 978­1­59327­867­0 Publisher: William Pollock Production Editor: Meg Sneeringer Cover Illustration: Josh Ellingson Developmental Editor: Annie Choi Technical Reviewer: Patrick Gaunt Copyeditor: Barton D. Reed Compositors: David Van Ness and Meg Sneeringer Proofreader: James Fraleigh The following images are reproduced with permission: Figure 10­2 by Acadac mixed from originals made by Avsa (https://commons.wikimedia.org/wiki/File:Britain­fractal­coastline­ 100km.png#/media/File:Britain­fractalcoastline­combined.jpg; CC­BY­SA­3.0); Figure 11­19 by Fabienne Serriere, https://knityak.com/. For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly: Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
📄 Page 4
No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; info@nostarch.com www.nostarch.com A catalog record of this book is available from the Library of Congress. 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 authors 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.
📄 Page 5
INTRODUCTION Which approach shown in Figure 1 would you prefer? On the left, you see an example of a traditional approach to teaching math, involving definitions, propositions, and proofs. This method requires a lot of reading and odd symbols. You’d never guess this had anything to do with geometric figures. In fact, this text explains how to find the centroid, or the center, of a triangle. But traditional approaches like this don’t tell us why we should be interested in finding the center of a triangle in the first place. Figure 1: Two approaches to teaching about the centroid Next to this text, you see a picture of a dynamic sketch with a hundred or so rotating triangles. It’s a challenging programming project, and if you want it to rotate the right History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
📄 Page 6
way (and look cool), you have to find the centroid of the triangle. In many situations, making cool graphics is nearly impossible without knowing the math behind geometry, for example. As you’ll see in this book, knowing a little of the math behind triangles, like the centroid, will make it easy to create our artworks. A student who knows math and can create cool designs is more likely to delve into a little geometry and put up with a few square roots or a trig function or two. A student who doesn’t see any outcome, and is only doing homework from a textbook, probably doesn’t have much motivation to learn geometry. In my eight years of experience as a math teacher and three years of experience as a computer science teacher, I’ve met many more math learners who prefer the visual approach to the academic one. In the process of creating something interesting, you come to understand that math is not just following steps to solve an equation. You see that exploring math with programming allows for many ways to solve interesting problems, with many unforeseen mistakes and opportunities for improvements along the way. This is the difference between school math and real math. THE PROBLEM WITH SCHOOL MATH What do I mean by “school math” exactly? In the US in the 1860s, school math was preparation for a job as a clerk, adding columns of numbers by hand. Today, jobs are different, and the preparation for these jobs needs to change, too. People learn best by doing. This hasn’t been a daily practice in schools, though, which tend to favor passive learning. “Doing” in English and history classes might mean students write papers or give presentations, and science students perform experiments, but what do math students do? It used to be that all you could actively “do” in math class was solve equations, factor polynomials, and graph functions. But now that computers can do most of those calculations for us, these practices are no longer sufficient. Simply learning how to automate solving, factoring, and graphing is not the final goal. Once a student has learned to automate a process, they can go further and deeper into a topic than was ever possible before. Figure 2 shows a typical math problem you’d find in a textbook, asking students to define a function, “f(x),” and evaluate it for a ton of values.
📄 Page 7
Figure 2: A traditional approach to teaching functions This same format goes on for 18 more questions! This kind of exercise is a trivial problem for a programming language like Python. We could simply define the function f(x) and then plug in the values by iterating over a list, like this: import math def f(x):     return math.sqrt(x + 3) ­ x + 1 #list of values to plug in for x in [0,1,math.sqrt(2),math.sqrt(2)­1]:     print("f({:.3f}) = {:.3f}".format(x,f(x))) The last line just makes the output pretty while rounding all the solutions to three decimal places, as shown here: f(0.000) = 2.732 f(1.000) = 2.000 f(1.414) = 1.687 f(0.414) = 2.434 In programming languages like Python, JavaScript, Java, and so on, functions are a vitally important tool for transforming numbers and other objects—even other functions! Using Python, you can give a descriptive name to a function, so it’s easier to understand what’s going on. For example, you can name a function that calculates the
📄 Page 8
area of a rectangle by calling it calculateArea(), like this: def calculateArea(width,height): A math textbook published in the 21st century, decades after Benoit Mandelbrot first generated his famous fractal on a computer when working for IBM, shows a picture of the Mandelbrot set and gushes over the discovery. The textbook describes the Mandelbrot set, which is shown in Figure 3, as “a fascinating mathematical object derived from the complex numbers. Its beautiful boundary illustrates chaotic behavior.” Figure 3: The Mandelbrot set The textbook then takes the reader through a painstaking “exploration” to show how to transform a point in the complex plane. But the student is only shown how to do this on a calculator, which means only two points can be transformed (iterated seven times) in a reasonable amount of time. Two points. In this book, you’ll learn how to do this in Python, and you’ll make the program transform hundreds of thousands of points automatically and even create the Mandelbrot set you see above! ABOUT THIS BOOK
📄 Page 9
This book is about using programming tools to make math fun and relevant, while still being challenging. You’ll make graphs to show all the possible outputs of a function. You’ll make dynamic, interactive works of art. You’ll even make an ecosystem with sheep that move around, eat grass, and multiply, and you’ll create virtual organisms that try to find the shortest route through a bunch of cities while you watch! You’ll do this using Python and Processing in order to supercharge what you can do in math class. This book is not about skipping the math; it’s about using the newest, coolest tools out there to get creative and learn real computer skills while discovering the connections between math, art, science, and technology. Processing will provide the graphics, shapes, motion, and colors, while Python does the calculating and follows your instructions behind the scenes. For each of the projects in this book, you’ll build the code up from scratch, starting from a blank file, and checking your progress at every step. Through making mistakes and debugging your own programs, you’ll get a much deeper understanding of what each block of code does. WHO SHOULD USE THIS BOOK This book is for anyone who’s learning math or who wants to use the most modern tools available to approach math topics like trigonometry and algebra. If you’re learning Python, you can use this book to apply your growing programming skills to nontrivial projects like cellular automata, genetic algorithms, and computational art. Teachers can use the projects in this book to challenge their students or to make math more approachable and relevant. What better way to teach matrices than to save a bunch of points to a matrix and use them to draw a 3D figure? When you know Python, you can do this and much more. WHAT’S IN THIS BOOK? This book begins with three chapters that cover basic Python concepts you’ll build on to explore more complicated math. The next nine chapters explore math concepts and problems that you can visualize and solve using Python and Processing. You can try the exercises peppered throughout the book to apply what you learned and challenge yourself. Chapter 1: Drawing Polygons with Turtles teaches basic programming concepts like loops, variables, and functions using Python’s built-in turtle module.
📄 Page 10
Chapter 2: Making Tedious Arithmetic Fun with Lists and Loops goes deeper into programming concepts like lists and Booleans. Chapter 3: Guessing and Checking with Conditionals applies your growing Python skills to problems like factoring numbers and making an interactive number-guessing game. Chapter 4: Transforming and Storing Numbers with Algebra ramps up from solving simple equations to solving cubic equations numerically and by graphing. Chapter 5: Transforming Shapes with Geometry shows you how to create shapes and then multiply, rotate, and spread them all over the screen. Chapter 6: Creating Oscillations with Trigonometry goes beyond right triangles and lets you create oscillating shapes and waves. Chapter 7: Complex Numbers teaches you how to use complex numbers to move points around the screen, creating designs like the Mandelbrot set. Chapter 8: Using Matrices for Computer Graphics and Systems of Equations takes you into the third dimension, where you’ll translate and rotate 3D shapes and solve huge systems of equations with one program. Chapter 9: Building Objects with Classes covers how to create one object, or as many as your computer can handle, with roaming sheep and delicious grass locked in a battle for survival. Chapter 10: Creating Fractals Using Recursion shows how recursion can be used as a whole new way to measure distances and create wildly unexpected designs. Chapter 11: Cellular Automata teaches you how to generate and program cellular automata to behave according to rules you make. Chapter 12: Solving Problems Using Genetic Algorithms shows you how to harness the theory of natural selection to solve problems we couldn’t solve in a million years otherwise! DOWNLOADING AND INSTALLING PYTHON The easiest way to get started is to use the Python 3 software distribution, which is available for free at https://www.python.org/. Python has become one of the most popular programming languages in the world. It’s used to create websites like Google,
📄 Page 11
YouTube, and Instagram, and researchers at universities all over the world use it to crunch numbers in various fields, from astronomy to zoology. The latest version released to date is Python 3.7. Go to https://www.python.org/downloads/ and choose the latest version of Python 3, as shown in Figure 4. Figure 4: The official website of the Python Software Foundation Figure 5: Click the downloaded file to start the install You can choose the version for your operating system. The site detected that I was using Windows. Click the file when the download is complete, as shown in Figure 5. Follow the directions, and always choose the default options. It might take a few minutes to install. After that, search your system for “IDLE.” That’s the Python IDE, or integrated development environment, which is what you’ll need to write Python code. Why “IDLE”? The Python programming language was named after the Monty Python comedy troupe, and one of the members is Eric Idle. STARTING IDLE Find IDLE on your system and open it.
📄 Page 12
Figure 6: Opening IDLE on Windows A screen called a “shell” will appear. You can use this for the interactive coding environment, but you’ll want to save your code. Click File▸New File or press ALT­N, and a file will appear (see Figure 7). Figure 7: Python’s interactive shell (left) and a new module (file) window, ready for code! This is where you’ll write your Python code. We will also use Processing, so let’s go over how to download and install Processing next. INSTALLING PROCESSING There’s a lot you can do with Python, and we’ll use IDLE a lot. But when we want to do some heavy­duty graphics, we’re going to use Processing. Processing is a professional­ level graphics library used by coders and artists to make dynamic, interactive artwork and graphics. Go to https://processing.org/download/ and choose your operating system, as shown in Figure 8.
📄 Page 13
Figure 8: The Processing website Figure 9: Where to find other Processing modes, like the Python mode we’ll be using Download the installer for your operating system by clicking it and following the
📄 Page 14
instructions. Double­click the icon to start Processing. This defaults to Java mode. Click Java to open the drop­down menu, as shown in Figure 9, and then click Add Mode. Select Python Mode▸Install. It should take a minute or two, but after this you’ll be able to code in Python with Processing. Now that you’ve set up Python and Processing, you’re ready to start exploring math!
📄 Page 15
PART I HITCHIN’ UP YOUR PYTHON WAGON aylists story opics utorials ffers & Deals ghlights ettings Support Sign Out
📄 Page 16
1 DRAWING POLYGONS WITH THE TURTLE MODULE Centuries ago a Westerner heard a Hindu say the Earth rested on the back of a turtle. When asked what the turtle was standing on, the Hindu explained, “It’s turtles all the way down.” Before you can start using math to build all the cool things you see in this book, you’ll need to learn how to give instructions to your computer using a programming language called Python. In this chapter you’ll get familiar with some basic programming concepts like loops, variables, and functions by using Python’s built­in turtle tool to draw different shapes. As you’ll see, the turtle module is a fun way to learn about Python’s basic features and get a taste of what you’ll be able to create with programming. PYTHON’S TURTLE MODULE The Python turtle tool is based on the original “turtle” agent from the Logo programming language, which was invented in the 1960s to make computer programming more accessible to everyone. Logo’s graphical environment made interacting with the computer visual and engaging. (Check out Seymour Papert’s brilliant book Mindstorms for more great ideas for learning math using Logo’s virtual turtles.) The creators of the Python programming language liked the Logo turtles so much that they wrote a module called turtle in Python to copy the Logo turtle functionality. Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
📄 Page 17
Python’s turtle module lets you control a small image shaped like a turtle, just like a video game character. You need to give precise instructions to direct the turtle around the screen. Because the turtle leaves a trail wherever it goes, we can use it to write a program that draws different shapes. Let’s begin by importing the turtle module! IMPORTING THE TURTLE MODULE Open a new Python file in IDLE and save it as myturtle.py in the Python folder. You should see a blank page. To use turtles in Python, you have to import the functions from the turtle module first. A function is a set of reusable code for performing a specific action in a program. There are many built­in functions you can use in Python, but you can also write your own functions (you’ll learn how to write your own functions later in this chapter). A module in Python is a file that contains predefined functions and statements that you can use in another program. For example, the turtle module contains a lot of useful code that was automatically downloaded when you installed Python. Although functions can be imported from a module in many ways, we’ll use a simple one here. In the myturtle.py file you just created, enter the following at the top: from turtle import * The from command indicates that we’re importing something from outside our file. We then give the name of the module we want to import from, which is turtle in this case. We use the import keyword to get the useful code we want from the turtle module. We use the asterisk (*) here as a wildcard command that means “import everything from that module.” Make sure to put a space between import and the asterisk. Save the file and make sure it’s in the Python folder; otherwise, the program will throw an error. WARNING Do not save the file as turtle.py. This filename already exists and will cause a conflict with the import from the turtle module! Anything else will work: myturtle.py, turtle2.py, mondayturtle.py, and so on. MOVING YOUR TURTLE
📄 Page 18
MOVING YOUR TURTLE Now that you’ve imported the turtle module, you’re ready to enter instructions to move the turtle. We’ll use the forward() function (abbreviated as fd) to move the turtle forward a certain number of steps while leaving a trail behind it. Note that forward() is one of the functions we just imported from the turtle module. Enter the following to make the turtle go forward: forward(100) Here, we use the forward() function with the number 100 inside parentheses to indicate how many steps the turtle should move. In this case, 100 is the argument we pass to the forward() function. All functions take one or more arguments. Feel free to pass other numbers to this function. When you press F5 to run the program, a new window should open with an arrow in the center, as shown in Figure 1­1. Figure 1­1: Running your first line of code! As you can see, the turtle started in the middle of the screen and walked forward 100 steps (it’s actually 100 pixels). Notice that the default shape is an arrow, not a turtle, and the default direction the arrow is facing is to the right. To change the arrow into a turtle, update your code so that it looks like this:
📄 Page 19
myturtle.py from turtle import * forward(100) shape('turtle') As you can probably tell, shape() is another function defined in the turtle module. It lets you change the shape of the default arrow into other shapes, like a circle, a square, or an arrow. Here, the shape() function takes the string value 'turtle' as its argument, not a number. (You’ll learn more about strings and different data types in the next chapter.) Save and run the myturtle.py file again. You should see something like Figure 1­2. Figure 1­2: Changing the arrow into a turtle! Now your arrow should look like a tiny turtle! CHANGING DIRECTIONS The turtle can go only in the direction it’s facing. To change the turtle’s direction, you must first make the turtle turn a specified number of degrees using the right() or left() function and then go forward. Update your myturtle.py program by adding the last two lines of code shown next: myturtle.py
📄 Page 20
from turtle import * forward(100) shape('turtle') right(45) forward(150) Here, we’ll use the right() function (or rt() for short) to make the turtle turn right 45 degrees before moving forward by 150 steps. When you run this code, the output should look like Figure 1­3. Figure 1­3: Changing turtle’s direction As you can see, the turtle started in the middle of the screen, went forward 100 steps, turned right 45 degrees, and then went forward another 150 steps. Notice that Python runs each line of code in order, from top to bottom. EXERCISE 1­1: SQUARE DANCE Return to the myturtle.py program. Your first challenge is to modify the code in the program using only the forward and right functions so that the turtle draws a square. REPEATING CODE WITH LOOPS Every programming language has a way to automatically repeat commands a given number of times. This is useful because it saves you from having to type out the same code over and over and cluttering your program. It also helps you avoid typos that can prevent your program from running properly. USING THE FOR LOOP In Python we use the for loop to repeat code. We also use the range keyword to specify the number of times we go through the loop. Open a new program file in IDLE, save it
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List