Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!
Ebook530 pages3 hours

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!

Rating: 3.5 out of 5 stars

3.5/5

()

Read preview

About this ebook

Doing Math with Python shows you how to use Python to delve into high school–level math topics like statistics, geometry, probability, and calculus. You’ll start with simple projects, like a factoring program and a quadratic-equation solver, and then create more complex projects once you’ve gotten the hang of things.

Along the way, you’ll discover new ways to explore math and gain valuable programming skills that you’ll use throughout your study of math and computer science. Learn how to:
–Describe your data with statistics, and visualize it with line graphs, bar charts, and scatter plots
–Explore set theory and probability with programs for coin flips, dicing, and other games of chance
–Solve algebra problems using Python’s symbolic math functions
–Draw geometric shapes and explore fractals like the Barnsley fern, the Sierpinski triangle, and the Mandelbrot set
–Write programs to find derivatives and integrate functions

Creative coding challenges and applied examples help you see how you can put your new math and coding skills into practice. You’ll write an inequality solver, plot gravity’s effect on how far a bullet will travel, shuffle a deck of cards, estimate the area of a circle by throwing 100,000 "darts" at a board, explore the relationship between the Fibonacci sequence and the golden ratio, and more.

Whether you’re interested in math but have yet to dip into programming or you’re a teacher looking to bring programming into the classroom, you’ll find that Python makes programming easy and practical. Let Python handle the grunt work while you focus on the math.

Uses Python 3
LanguageEnglish
PublisherNo Starch Press
Release dateAug 1, 2015
ISBN9781593277192
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!

Related to Doing Math with Python

Related ebooks

Programming For You

View More

Reviews for Doing Math with Python

Rating: 3.7142856 out of 5 stars
3.5/5

7 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Doing Math with Python - Amit Saha

    Introduction

    This book’s goal is to bring together three topics near to my heart—programming, math, and science. What does that mean exactly? Within these pages, we’ll programmatically explore high school–level topics, like manipulating units of measurement; examining projectile motion; calculating mean, median, and mode; determining linear correlation; solving algebraic equations; describing the motion of a simple pendulum; simulating dice games; creating geometric shapes; and finding the limits, derivatives, and integrals of functions. These are familiar topics for many, but instead of using pen and paper, we’ll use our computer to explore them.

    We’ll write programs that will take numbers and formulas as input, do the tedious calculations needed, and then spit out the solution or draw a graph. Some of these programs are powerful calculators for solving math problems. They find the solutions to equations, calculate the correlation between sets of data, and determine the maximum value of a function, among other tasks. In other programs, we’ll simulate real-life events, such as projectile motion, a coin toss, or a die roll. Using programs to simulate such events gives us an easy way to analyze and learn more about them.

    You’ll also find topics that would be extremely difficult to explore without programs. For example, drawing fractals by hand is tedious at best and close to impossible at worst. With a program, all we need to do is run a for loop with the relevant operation in the body of the loop.

    I think you’ll find that this new context for doing math makes learning both programming and math more exciting, fun, and rewarding.

    Who Should Read This Book

    If you yourself are learning programming, you’ll appreciate how this book demonstrates ways to solve problems with computers. Likewise, if you teach such learners, I hope you find this book useful to demonstrate the application of programming skills beyond the sometimes abstract world of computer science.

    This book assumes the reader knows the absolute basics of Python programming using Python 3—specifically, what a function is, function arguments, the concept of a Python class and class objects, and loops. Appendix B covers some of the other Python topics that are used by the programs, but this book doesn’t assume knowledge of these additional topics. If you find yourself needing more background, I recommend reading Python for Kids by Jason Briggs (No Starch Press, 2013).

    What’s in This Book?

    This book consists of seven chapters and two appendices. Each chapter ends with challenges for the reader. I recommend giving these a try, as there’s much to learn from trying to write your own original programs. Some of these challenges will ask you to explore new topics, which is a great way to enhance your learning.

    Chapter 1, Working with Numbers, starts off with basic mathematical operations and gradually moves on to topics requiring a higher level of math know-how.

    Chapter 2, Visualizing Data with Graphs, discusses creating graphs from data sets using the matplotlib library.

    Chapter 3, Describing Data with Statistics, continues the theme of processing data sets, covering basic statistical concepts—mean, median, mode, and the linear correlation of variables in a data set. You’ll also learn to handle data from CSV files, a popular file format for distributing data sets.

    Chapter 4, Algebra and Symbolic Math with SymPy, introduces symbolic math using the SymPy library. It begins with the basics of representing and manipulating algebraic expressions before introducing more complicated matters, such as solving equations.

    Chapter 5, Playing with Sets and Probability, discusses the representation 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 mathematical 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.

    Scripts, Solutions, and Hints

    This book’s companion site is http://www.nostarch.com/doingmathwithpython/. Here, you can download all the programs in this book as well as hints and solutions for the challenges. You’ll also find links to additional math, science, and Python resources I find useful as well as any corrections or updates to the book itself.

    Software is always changing; a new release of Python, SymPy, or matplotlib may cause a certain functionality demonstrated in this book to behave differently. You’ll find any of these changes noted on the website.

    I hope this book makes your journey into computer programming more fun and immediately relevant. Let’s do some math!

    1

    Working with Numbers

    Let’s take our first steps toward using Python to explore the world of math and science. We’ll keep it simple now so you can get a handle on using Python itself. We’ll start by performing basic mathematical operations, and then we’ll write simple programs for manipulating and understanding numbers. Let’s get started!

    Basic Mathematical Operations

    The Python interactive shell is going to be our friend in this book. Start the Python 3 IDLE shell and say hello (see Figure 1-1) by typing print('Hello IDLE') and then pressing ENTER. (For instructions on how to install Python and start IDLE, see Appendix A.) IDLE obeys your command and prints the words back to the screen. Congratulations—you just wrote a program!

    When you see the >>> prompt again, IDLE is ready for more instructions.

    Figure 1-1: Python 3 IDLE shell

    Python can act like a glorified calculator, doing simple computations. Just type an expression and Python will evaluate it. After you press ENTER, the result appears immediately.

    Give it a try. You can add and subtract numbers using the addition (+) and subtraction (–) operators. For example:

    >>> 1 + 2

    3

    >>> 1 + 3.5

    4.5

    >>> -1 + 2.5

    1.5

    >>> 100 – 45

    55

    >>> -1.1 + 5

    3.9

    To multiply, use the multiplication (*) operator:

    >>> 3 * 2

    6

    >>> 3.5 * 1.5

    5.25

    To divide, use the division (/) operator:

    >>> 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

    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 operation (-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 n¹/² and the cube root as n¹/³:

    >>> 8 ** (1/3)

    2.0

    As this example shows, you can use parentheses to combine mathematical operations into more complicated expressions. Python will evaluate the expression following the standard PEMDAS rule for the order of calculations—parentheses, exponents, multiplication, division, addition, and subtraction. Consider the following two expressions—one without parentheses and one with:

    >>> 5 + 5 * 5

    30

    >>> (5 + 5) * 5

    50

    In the first example, Python calculates the multiplication first: 5 times 5 is 25; 25 plus 5 is 30. In the second example, the expression within the parentheses is evaluated first, just as we’d expect: 5 plus 5 is 10; 10 times 5 is 50.

    These are the absolute basics of manipulating numbers in Python. Let’s now learn how we can assign names to numbers.

    Labels: Attaching Names to Numbers

    As we start designing more complex Python programs, we’ll assign names to numbers—at times for convenience, but mostly out of necessity. Here’s a simple example:

    ➊ >>> a = 3

       >>> a + 1

       4

    ➋ >>> a = 5

       >>> a + 1

       6

    At ➊, we assign the name a to the number 3. When we ask Python to evaluate the result of the expression a + 1, it sees that the number that a refers to is 3, and then it adds 1 and displays the output (4). At ➋, we change the value of a to 5, and this is reflected in the second addition operation. Using the name a is convenient because you can simply change the number that a points to and Python uses this new value when a is referred to anywhere after that.

    This kind of name is called a label. You may have been introduced to the term variable to describe the same idea elsewhere. However, considering that variable is also a mathematical term (used to refer to something like x in the equation x + 2 = 3), in this book I use the term variable only in the context of mathematical equations and expressions.

    Different Kinds of Numbers

    You may have noticed that I’ve used two kinds of numbers to demonstrate the mathematical operations—numbers without a decimal point, which you already know as integers, and numbers with a decimal point, which programmers call floating point numbers. We humans have no trouble recognizing and working with numbers whether they’re written as integers, floating point decimals, fractions, or roman numerals. But in some of the programs that we write in this book, it will only make sense to perform a task on a particular type of number, so we’ll often have to write a bit of code to have the programs check whether the numbers we input are of the right type.

    Python considers integers and floating point numbers to be different types. If you use the function type(), Python will tell you what kind of number you’ve just input. For example:

    >>> type(3)

    >>> type(3.5)

    >>> type(3.0)

    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 situations, 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 number 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 integer. 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.

    Working with Fractions

    Python can also handle fractions, but to do that, we’ll need to use Python’s fractions module. You can think of a module as a program written by someone else that you can use in your own programs. A module can include classes, functions, and even label definitions. It can be part of Python’s standard library or distributed from a third-party location. In the latter case, you would have to install the module before you could use it.

    The fractions module is part of the standard library, meaning that it’s already installed. It defines a class Fraction, which is what we’ll use to enter fractions into our programs. Before we can use it, we’ll need to import it, which is a way of telling Python that we want to use the class from this module. Let’s see a quick example—we’ll create a new label, f, which refers to the fraction 3/4:

    ➊ >>> from fractions import Fraction

    ➋ >>> f = Fraction(3, 4)

    ➌ >>> f

       Fraction(3, 4)

    We first import the Fraction class from the fractions module ➊. Next, we create an object of this class by passing the numerator and denominator as parameters ➋. This creates a Fraction object for the fraction 3/4. When we print the object ➌, Python displays the fraction in the form Fraction(numerator, denominator).

    The basic mathematical operations, including the comparison operations, are all valid for fractions. You can also combine a fraction, an integer, and a floating point number in a single expression:

    >>> Fraction(3, 4) + 1 + 1.5

    3.25

    When you have a floating point number in an expression, the result of the expression is returned as a floating point number.

    On the other hand, when you have only a fraction and an integer in the expression, the result is a fraction, even if the result has a denominator of 1.

    >>> Fraction(3, 4) + 1 + Fraction(1/4)

    Fraction(2, 1)

    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)

    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)

    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 imaginary 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:

    >>> (z.real ** 2 + z.imag ** 2) ** 0.5

    3.605551275463989

    A simpler way to find the magnitude of a complex number is with the abs() function. The abs() function returns the absolute value when called with a real number as its argument. For example, abs(5) and abs(-5) both return 5. However, for complex numbers, it returns the magnitude:

    >>> 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.

    Getting User Input

    As we start to write programs, it will help to have a nice, simple way to accept user input via the input() function. That way, we can write programs that ask a user to input a number, perform specific operations on that number, and then display the results of the operations. Let’s see it in action:

    ➊ >>> a = input()

    ➋ 1

    At ➊, we call the input() function, which waits for you to type something, as shown at ➋, and press ENTER. The input provided is stored in a:

       >>> a

    ➌ '1'

    Notice the single quotes around 1 at ➌. The input() function returns the input as a string. In Python, a string is any set of characters between two quotes. When you want to create a string, either single quotes or double quotes can be used:

    >>> s1 = 'a string'

    >>> s2 = a string

    Here, both s1 and s2 refer to the same string.

    Even if the only characters in a string are numbers, Python won’t treat that string as a number unless we get rid of those quotation marks. So before we can perform any mathematical operations with the input, we’ll have to convert it into the correct number type. A string can be converted to an integer or floating point number using the int() or float() function, respectively:

    >>> 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 important to note, however, that the int() function cannot convert a string containing 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):

      File , line 1, in 

        int('2.0')

    ValueError: invalid literal for int() with base 10: '2.0'

    This is an example of an exception—Python’s way of telling you that it cannot continue executing your program because of an error. In this case, the exception is of the type ValueError. (For a quick refresher on exceptions, see Appendix B.)

    Similarly, when you supply a fractional number such as 3/4 as an input, Python cannot convert it into an equivalent floating point number or integer. Once again, a ValueError exception is raised:

    >>> a = float(input())

    3/4

    Traceback (most recent call last):

      File , line 1, in 

        a=float(input())

    ValueError: could not convert string to float: '3/4'

    You may find it useful to perform the conversion in a try...except block so that you can handle this exception and alert the user that the program has encountered an invalid input. We’ll look at

    Enjoying the preview?
    Page 1 of 1