1 Learning math with code

This chapter covers

  • Solving lucrative problems with math and software
  • Avoiding common pitfalls in learning math
  • Building on intuition from programming to understand math
  • Using Python as a powerful and extensible calculator

Math is like baseball, or poetry, or fine wine. Some people are so fascinated by math that they devote their whole lives to it, while others feel like they just don’t get it. You’ve probably already been forced into one camp or another by twelve years of compulsory math education in school.

What if we learned about fine wine in school like we learned math? I don’t think I’d like wine at all if I got lectured on grape varietals and fermentation techniques for an hour a day, five days a week. Maybe in such a world, I’d need to consume three or four glasses for homework as assigned by the teacher. Sometimes this would be a delicious educational experience, but sometimes I might not feel like getting loaded on a school night. My experience in math class went something like that, and it turned me off of the subject for a while. Like wine, mathematics is an acquired taste, and a daily grind of lectures and assignments is no way to refine one’s palate.

It’s easy to think you’re either cut out for math or you aren’t. If you already believe in yourself, and you’re excited to start learning, that’s great! Otherwise, this chapter is designed for those less optimistic. Feeling intimidated by math is so common, it has a name: math anxiety . I hope to dispel any anxiety you might have and show you that math can be a stimulating experience rather than a frightening one. All you need are the right tools and the right mindset.

The main tool for learning in this book is the Python programming language. I’m guessing that when you learned math in high school, you saw it written on the blackboard and not in computer code. That’s a shame, because a high-level programming language is far more powerful than a blackboard and far more versatile than whatever overpriced calculator you may have used. An advantage of meeting math in code is that the ideas have to be precise enough for a computer to understand, and there’s never any hand-waving about what new symbols mean.

As with learning any new subject, the best way to set yourself up for success is to want to learn. There are plenty of good reasons for this. You could be intrigued by the beauty of mathematical concepts or enjoy the “brain-teaser” feel of math problems. Maybe there’s an app or game that you dream of building, and you need to write some mathematical code to make it work. For now, I’ll focus on a more pragmatic kind of motivation−solving mathematical problems with software can make you a lot of money.

1.1 Solving lucrative problems with math and software

A classic criticism you hear in high school math class is, “When am I ever going to use this stuff in real life?” Our teachers told us that math would help us succeed professionally and make money. I think they were right about this, even though their examples were off. For instance, I don’t calculate my compounding bank interest by hand (and neither does my bank). Maybe if I became a construction site surveyor as my trigonometry teacher suggested, I’d be using sines and cosines every day to earn my paycheck.

It turns out the “real world” applications from high school textbooks aren’t that useful. Still, there are real applications of math out there, and some of them are mind-bogglingly lucrative. Many are solved by translating the right mathematical idea into usable software. I’ll share some of my favorite examples.

1.1.1 Predicting financial market movements

We’ve all heard legends of stock traders making millions of dollars by buying and selling the right stocks at the right time. Based on the movies I’ve seen, I always picture a trader as a middle-aged man in a suit yelling at his broker over a cell phone while driving around in a sports car. Maybe this stereotype was spot-on at one point, but the situation is different today.

Holed up in back offices of skyscrapers all over Manhattan are thousands of people called quants . Quants, otherwise known as quantitative analysts, design mathematical algorithms to automatically trade stocks and earn a profit. They don’t wear suits and they don’t spend time yelling on their cell phones, but I’m sure many of them own very nice sports cars.

So how does a quant write a program that automatically makes money? The best answers to that question are closely-guarded trade secrets, but you can be sure they involve a lot of math. We can look at a brief example to get a sense of how an automated trading strategy might work.

Stocks are types of financial assets that represent ownership stakes in companies. When the market perceives a company is doing well, its stock price goes up−buying the stock becomes more costly and selling it becomes more rewarding. Stock prices change erratically and in real time. Figure 1.1 shows how a graph of a stock price over a day of trading might look.

Figure 1.1 Typical graph of a stock price over time

If you bought a thousand shares of this stock for $24 around minute 100 and sold them for $38 at minute 400, you would make $14,000 for the day. Not bad! The challenge is that you’d have to know in advance that the stock was going up, and that minutes 100 and 400 were the best times to buy and sell, respectively. It may not be possible to predict the exact lowest or highest price points, but maybe you can find relatively good times to buy and sell throughout the day. Let’s look at a way to do this mathematically.

We could measure whether the stock is going up or down by finding a line of “best fit” that approximately follows the direction the price is moving. This process is called linear regression , and we cover it in part 3 of this book. Based on the variability of data, we can calculate two more lines above and below the “best fit” line that show the region in which the price is wobbling up and down. Overlaid on the price graph, figure 1.2 shows that the lines follow the trend nicely.

Figure 1.2 Using linear regression to identify a trend in changing stock prices

With a mathematical understanding of the price movement, we can then write code to automatically buy when the price is going through a low fluctuation relative to its trend and to sell when the price goes back up. Specifically, our program could connect to the stock exchange over the network and buy 100 shares when the price crosses the bottom line and sell 100 shares when the price crosses the top line. Figure 1.3 illustrates one such profitable trade: buying at around $27.80 and selling at around $32.60 makes you $480 in an hour.

Figure 1.3 Buying and selling according to our rules-based software to make a profit

I don’t claim I’ve shown you a complete or viable strategy here, but the point is that with the right mathematical model, you can make a profit automatically. At this moment, some unknown number of programs are building and updating models measuring the predicted trend of stocks and other financial instruments. If you write such a program, you can enjoy some leisure time while it makes money for you!

1.1.2 Finding a good deal

Maybe you don’t have deep enough pockets to consider risky stock trading. Math can still help you make and save money in other transactions like buying a used car, for example. New cars are easy-to-understand commodities. If two dealers are selling the same car, you obviously want to buy from the dealer that has the lowest cost. But used cars have more numbers associated with them: an asking price, as well as mileage and model year. You can even use the duration that a particular used car has been on the market to assess its quality: the longer the duration, the more suspicious you might be.

In mathematics, objects you can describe with ordered lists of numbers are called vectors , and there is a whole field (called linear algebra ) dedicated to studying them. For example, a used car might correspond to a four-dimensional vector, meaning a four-tuple of numbers:

(2015, 41429, 22.27, 16980)

These numbers represent the model year, mileage, days on the market, and asking price, respectively. A friend of mine runs a site called CarGraph.com that aggregates data on used cars for sale. At the time of writing, it shows 101 Toyota Priuses for sale, and it gives some or all of these four pieces of data for each one. The site also lives up to its name and visually presents the data in a graph (figure 1.4). It’s hard to visualize four-dimensional objects, but if you choose two of the dimensions like price and mileage, you can graph them as points on a scatter plot.

Figure 1.4 A graph of price vs. mileage for used Priuses from CarGraph.com

Figure 1.5 Fitting an exponential decline curve to price vs. mileage data for used Toyota Priuses

We might be interested in drawing a trend line here too. Every point on this graph represents someone’s opinion of a fair price, so the trend line would aggregate these opinions together into a more reliable price at any mileage. In figure 1.5, I decided to fit to an exponential decline curve rather than a line, and I omitted some of the nearly new cars selling for below retail price.

To make the numbers more manageable, I converted the mileage values to tens of thousands of miles, so a mileage of 5 represents 50,000 miles. Calling p the price and m the mileage, the eq uation for the curve of best fit is as follows:

p = $26,500 · (0.905)m

Equation 1.1

Equation 1.1 shows that the best fit price is $26,500 times 0.905 raised to the power of the mileage. Plugging the values into the equation, I find that if my budget is $10,000, then I should buy a Prius with about 97,000 miles on it (figure 1.6). If I believe the curve indicates a fair price, then cars below the line should typically be good deals.

Figure 1.6 Finding the mileage I should expect on a used Prius for my $10,000 budget

But we can learn more from equation 1.1 than just how to find a good deal. It tells a story about how cars depreciate. The first number in the equation is $26,500, which is the exponential function’s understanding of the price at zero mileage. This is an impressively close match to the retail price of a new Prius. If we use a line of best fit, it implies a Prius loses a fixed amount of value with each mile driven. This exponential function says, instead, that it loses a fixed percentage of its value with each mile driven. After driving 10,000 miles, a Prius is only worth 0.905 or 90.5% of its original price according to this equation. After 50,000 miles, we multiply its price by a factor of (0.905)5 = 0.607. That tells us that it’s worth about 61% of what it was originally.

To make the graph in figure 1.6, I implemented a price(mileage) function in Python, which takes a mileage as an input (measured in 10,000s of miles) and returns the best-fit price as an output. Calculating price(0) − price(5) and price(5) − price(10) tells me that the first and second 50,000 miles driven cost about $10,000 and $6,300, respectively.

If we use a line of best fit instead of an exponential curve, it implies that the car depreciated at a fixed rate of $0.10 per mile. This suggests that every 50,000 miles of driving leads to the same depreciation of $5,000. Conventional wisdom says that the first miles you drive a new car are the most expensive, so the exponential function (equation 1.1) agrees with this, while a linear model does not.

Remember, this is only a two-dimensional analysis. We only built a mathematical model to relate two of the four numerical dimensions describing each car. In part 1, you learn more about vectors of various dimensions and how to manipulate higher-dimensional data. In p art 2, we cover different kinds of functions like linear functions and exponential functions, and we compare them by analyzing their rates of change. Finally, in part 3, we look at how to build mathematical models that incorporate all the dimensions of a data set to give us a more accurate picture.

1.1.3 Building 3D graphics and animations

Many of the most famous and financially successful software projects deal with multi-dimensional data, specifically three-dimensional or 3D data. Here I’m thinking of 3D animated movies and 3D video games that gross in the billions of dollars. For example, Pixar’s 3D animation software has helped them rake in over $13 billion at box offices. Activision’s Call of Duty franchise of 3D action games has earned over $16 billion, and Rockstar’s Grand Theft Auto V alone has brought in $6 billion.

Every one of these acclaimed projects is based on an understanding of how to do computations with 3D vectors, or triples of numbers of the form v = (x, y, z). A triple of

numbers is sufficient to locate a point in 3D space relative to a reference point called the origin . Figure 1.7 shows how each of the three numbers tells you how far to go in one of three perpendicular directions.

Figure 1.7 Labeling a point in 3D with a vector of three numbers, x, y, and z

Any 3D object from a clownfish in Finding Nemo to an aircraft carrier in Call of Duty can be defined for a computer as a collection of 3D vectors. In code, each of these objects looks like a list of triples of float values. With three triples of floats, we have three points in space that can define a triangle (figure 1.8). For instance,

triangle = [(2.3,1.1,0.9), (4.5,3.3,2.0), (1.0,3.5,3.9)]

Figure 1.8 Building a 3D triangle using a triple of float values for each of its corners

Combining many triangles, you can define the surface of a 3D object. Using more, smaller triangles, you can even make the result look smooth. Figure 1.9 shows six renderings of a 3D sphere using an increasing number of smaller and smaller triangles.

Figure 1.9 Three-dimensional (3D) spheres built out of the specified number of triangles.

In chapters 3 and 4, you learn how to use 3D vector math to turn 3D models into shaded 2D images like the ones in figure 1.9. You also need to make your 3D models smooth to make them realistic in a game or movie, and you need them to move and change in realistic ways. This means that your objects should obey the laws of physics, which are also expressed in terms of 3D vectors.

Suppose you’re a programmer for Grand Theft Auto V and want to enable a basic use case like shooting a bazooka at a helicopter. A projectile coming out of a bazooka starts at the protagonist’s location and then its position changes over time. You can use numeric subscripts to label the various positions it has over its flight, starting with v0 = (x0, y0, z0). As time elapses, the projectile arrives at new positions labeled by vectors v1 = (x1, y1, z1), v2 = (x2, y2, z2), and so on. The rates of change for the x, y, and z values are decided by the direction and speed of the bazooka. Moreover, the rates can change over time−the projectile increases its z position at a decreasing rate because of the continuous downward pull of gravity (figure 1.10).

Figure 1.10 The position vector of the projectile changes over time due to its initial speed and the pull of gravity.

As any experienced action gamer will tell you, you need to aim slightly above the helicopter to hit it! To simulate physics, you have to know how forces affect objects and cause continuous change over time. The math of continuous change is called calculus , and the laws of physics are usually expressed in terms of objects from calculus called differential equations . You learn how to animate 3D objects in chapters 4 and 5, and then how to simulate physics using ideas from calculus in part 2.

1.1.4 Modeling the physical world

My claim that mathematical software produces real financial value isn’t just speculation; I’ve seen the value in my own career. In 2013, I founded a company called Tachyus that builds software to optimize oil and gas production. Our software uses mathematical models to understand the flow of oil and gas underground to help producers extract it more efficiently and profitably. Using the insight it generates, our customers have achieved millions of dollars a year in cost savings and production increases.

To explain how our software works, you need to know a few pieces of oil terminology. Holes called wells are drilled into the ground until they reach the target layer of porous (sponge-like) rock containing oil. This layer of oil-rich rock underground is called a reservoir. Oil is pumped to the surface and is then sold to refiners who convert it into the products we use every day. A schematic of an oilfield (not to scale!) is shown in figure 1.11.

Over the past few years, the price of oil has varied significantly, but for our purposes, let’s say it’s worth $50 a barrel, where a barrel is a unit of volume equal to 42 gallons or about 159 liters. If by drilling wells and pumping effectively, a company is able to extract 1,000 barrels of oil per day (the volume of a few backyard swimming pools), it will have annual revenues in the tens of millions of dollars. Even a few percentage points of increased efficiency can mean a sizable amount of money.

Figure 1.11  A schematic diagram of an oilfield

The underlying question is what’s going on underground: where is the oil now and how is it moving? This is a complicated question, but it can also be answered by solving differential equations. The changing quantities here are not positions of a projectile, but rather locations, pressures, and flow rates of fluids underground. Fluid flow rate is a special kind of function that returns a vector, called a vector field. This means that fluid can flow at any rate in any three-dimensional direction, and that direction and rate can vary across different locations within the reservoir.

With our best guess for some of these parameters, we can use a differential equation called Darcy’s law to predict flow rate of liquid through a porous rock medium like sandstone. Figure 1.12 shows Darcy’s law, but don’t worry if some symbols are unfamiliar! The function named q representing flow rate is bold to indicate it returns a vector value.

Figure 1.12 Darcy’s law annotated for a physics equation, governing how fluid flows within a porous rock.

The most important part of this equation is the symbol that looks like an upside-down triangle, which represents the gradient operator in vector calculus. The gradient of the pressure function p(x, y, z) at a given spatial point (x, y, z) is the 3D vector q(x, y, z), indicating the direction of increasing pressure and the rate of increase in pressure at that point. The negative sign tells us that the 3D vector of flow rate is in the opposite direction. This equation states, in mathematical terms, that fluid flows from areas of high pressure to areas of low pressure.

Negative gradients are common in the laws of physics. One way to think of this is that nature is always seeking to move toward lower potential energy states. The potential energy of a ball on a hill depends on the altitude h of the hill at any lateral point x. If the height of a hill is given by a function h(x), the gradient points uphill while the ball rolls in the exact opposite direction (figure 1.13).

Figure 1.13 The positive gradient points uphill, while the negative gradient points downhill.

In chapter 11, you learn how to calculate gradients. There, I show you how to apply gradients to simulate physics and also to solve other mathematical problems. The gradient happens to be one of the most important mathematical concepts in machine learning as well.

I hope these examples have been more compelling and realistic than the real-world applications you heard in high school math class. Maybe, at this point, you’re convinced these math concepts are worth learning, but you’re worried that they might be too difficult. It’s true that learning math can be hard, especially on your own. To make it as smooth as possible, let’s talk about some of the pitfalls you can face as a math student and how I’ll help you avoid them in this book.

1.2 How not to learn math

There are plenty of math books out there, but not all of them are equally useful. I have quite a few programmer friends who tried to learn mathematical concepts like the ones in the previous section, either motivated by intellectual curiosity or by career ambitions. When they use traditional math textbooks as their main resource, they often get stuck and give up. Here’s what a typical unsuccessful math-learning story looks like.

1.2.1 Jane wants to learn some math

My (fictional) friend Jane is a full-stack web developer working at a medium-sized tech company in San Francisco. In college, Jane didn’t study computer science or any mathematical subjects in depth, and she started her career as a product manager. Over the last ten years, she picked up coding in Python and JavaScript and was able to transition into software engineering. Now, at her new job, she is one of the most capable programmers on the team, able to build the databases, web services, and user interfaces required to deliver important new features to customers. Clearly, she’s pretty smart!

Jane realizes that learning data science could help her design and implement better features at work, using data to improve the experience for her customers. Most days on the train to work, Jane reads blogs and articles about new technologies, and recently, she’s been amazed by a few about a topic called “deep learning.” One article talks about Google’s AlphaGo, powered by deep learning, which beat the top-ranked human players in the world in a board game. Another article showed stunning impressionist paintings generated from ordinary images, again using a deep learning system.

After reading these articles, Jane overheard that her friend-of-a-friend Marcus got a deep learning research job at a big tech company. Marcus supposedly gets paid over $400,000 a year in salary and stock. Thinking about the next step in her career, what more could Jane want than to work on a fascinating and lucrative problem?

Jane did some research and found an authoritative (and free!) resource online: the book Deep Learning by Goodfellow, et al., (MIT Press, 2016). The introduction read much like the technical blog posts she was used to and got her even more excited about learning the topic. But as she kept reading, the content of the book got harder. The first chapter covered the required math concepts and introduced a lot of terminology and notation that Jane had never seen. She skimmed it and tried to get on to the meat of the book, but it continued to get more difficult.

Jane decided she needed to pause her study of AI and deep learning until she learned some math. Fortunately, the math chapter of Deep Learning listed a reference on linear algebra for students who had never seen the topic before. She tracked down this textbook, Linear Algebra by Georgi Shilov (Dover, 1977), and discovered that it was 400 pages long and equally as dense as Deep Learning.

After spending an afternoon reading abstruse theorems about concepts like number fields, determinants, and cofactors, she called it quits. She had no idea how these concepts were going to help her write a program to win a board game or to generate artwork, and she no longer cared to spend dozens of hours with this dry material to find out.

Jane and I met to catch up over a cup of coffee. She told me about her struggles reading real AI literature because she didn’t know linear algebra. Recently, I’m hearing a lot of the same form of lamentation:

I’m trying to read about [new technology] but it seems like I need to learn [math topic] first.

Her approach was admirable: she tracked down the best resource for the subject she wanted to learn and sought out resources for prerequisites she was missing. But in taking that approach to its logical conclusion, she found herself in a nauseating “depth-first” search of technical literature.

1.2.2 Slogging through math textbooks

College-level math books like the linear algebra book Jane picked up tend to be very formulaic. Every section follows the same format: it defines some new terminology, states some facts (called theorems ) using that terminology, and then proves that those theorems are true.

This sounds like a good, logical order: you introduce the concept you’re talking about, state some conclusions that can be drawn, and then justify them. Then why is it so hard to read advanced mathematical textbooks?

The problem is that this is not how math is actually created. When you’re coming up with new mathematical ideas, there can be a long period of experimentation before you even find the right definitions. I think most professional mathematicians would describe their steps like this:

  1. Invent a game. For example, start playing with some mathematical objects by trying to list all of them, find patterns among them, or find one with a particular property.

  2. Form some conjectures. Speculate about some general facts you can state about your game and, at least, convince yourself these must be true.

  3. Develop some precise language to describe your game and your conjectures. After all, your conjectures won’t mean anything until you can communicate them.

  4. Finally, with some determination and luck, find a proof for your conjecture, showing why it needs to be true.

The main lesson to learn from this process is that you should start by thinking about big ideas, and the formalism can wait. Once you have a rough idea of how the math works, the vocabulary and notation become an asset for you rather than a distraction. Math textbooks usually work in the opposite order, so I recommend using textbooks as references rather than as introductions to new subjects.

Instead of reading traditional textbooks, the best way to learn math is to explore ideas and draw your own conclusions. However, you don’t have enough hours in the day to reinvent everything yourself. What is the right balance to strike? I’ll give you my humble opinion, which guides how I’ve written this non-traditional book about math.

1.3 Using your well-trained left brain

This book is designed for people who are either experienced programmers or for those who are excited to learn programming as they work through it. It’s great to write about math for an audience of programmers, because if you can write code, you’ve already trained your analytical left brain. I think the best way to learn math is with the help of a high-level programming language, and I predict that in the not-so-distant future, this will be the norm in math classrooms.

There are several specific ways programmers like you are well equipped to learn math. I list those here, not only to flatter you, but also to remind you what skills you already have that you can lean on in your mathematical studies.

1.3.1 Using a formal language

One of the first hard lessons you learn in programming is that you can’t write your code like you write simple English. If your spelling or grammar is slightly off when writing a note to a friend, they can probably still understand what you’re trying to say. But any syntactic error or misspelled identifier in code causes your program to fail. In some languages, even forgetting a semicolon at the end of an otherwise correct statement prevents the program from running. As another example, consider the two statements:

x = 5
5 = x

I could read either of these to mean that the symbol x has the value 5. But that’s not exactly what either of these means in Python, and in fact, only the first one is correct. The Python statement x = 5 is an instruction to set the variable x to have the value 5. On the other hand, you can’t set the number 5 to have the value x. This may seem pedantic, but you need to know it to write a correct program.

Another example that trips up novice programmers (and experienced ones as well!) is reference equality. If you define a new Python class and create two identical instances of it, they are not equal!

>>> class A(): pass
...
>>> A() == A()
False

You might expect two identical expressions to be equal, but that’s evidently not a rule in Python. Because these are different instances of the A class, they are not considered equal.

Be on the lookout for new mathematical objects that look like ones you know but don’t behave the same way. For instance, if the letters a and B represent numbers, then a · B = B · a. But, as you’ll learn in chapter 5, this is not necessarily the case if a and B are not numbers. If, instead, a and B are matrices, then the products a · B and B · a are different. In fact, it’s possible that only one of the products is even doable or that neither product is correct.

When you’re writing code, it’s not enough to write statements with correct syntax. The ideas that your statements represent need to make sense to be valid. If you apply the same care when you’re writing mathematical statements, you’ll catch your mistakes faster. Even better, if you write your mathematical statements in code, you’ll have the computer to help check your work.

1.3.2 Build your own calculator

Calculators are prevalent in math classes because it’s useful to check your work. You need to know how to multiply 6 by 7 without using your calculator, but it’s good to confirm that your answer of 42 is correct by consulting your calculator. The calculator also helps you save time once you’ve mastered mathematical concepts. If you’re doing trigonometry, and you need to know the answer to 3.14159 / 6, the calculator is there to handle it so you can instead think about what the answer means. The more a calculator can do out-of-the-box, the more useful it should theoretically be.

But sometimes our calculators are too complicated for our own good. When I started high school, I was required to get a graphing calculator and I got a TI-84. It had about 40 buttons, each with 2 to 3 different modes. I only knew how to use maybe 20 of them, so it was a cumbersome tool to learn how to use. The story was the same when I got my first ever calculator in first grade. There were only 15 buttons or so, but I didn’t know what some of them did. If I had to invent a first calculator for students, I would make it look something like the one in figure 1.14.

Figure 1.14 A calculator for students learning to count

This calculator only has two buttons. One of them resets the value to 1, and the other advances to the next number. Something like this would be the right “no-frills” tool for children learning to count. (My example may seem silly, but you can actually buy calculators like this! They are usually mechanical and sold as tally counters.)

Soon after you master counting, you want to practice writing numbers and adding them. The perfect calculator at that stage of learning might have a few more buttons (figure 1.15).

Figure 1.15 A calculator capable of writing whole numbers and adding them

There’s no need for buttons like , *, or ÷ to get in your way at this phase. As you solve subtraction problems like 5 2, you can still check your answer of 3 with this calculator by confirming the sum 3 + 2 = 5. Likewise, you can solve multiplication problems by adding numbers repeatedly. You could upgrade to a calculator that does all of the operations of arithmetic when you’re done exploring with this one.

I think an ideal calculator would be extensible, meaning that you could add more functionality to it as needed. For instance, you could add a button to your calculator for every new mathematical operation you learn. Once you got to algebra, maybe you could enable it to understand symbols like x or y in addition to numbers. When you

learned calculus, you could further enable it to understand and manipulate mathematical functions.

Extensible calculators that can hold many types of data seem far-fetched, but that’s exactly what you get when you use a high-level programming language. Python comes with arithmetic operations, a math module, and numerous third-party mathematical libraries you can pull in to make your programming environment more powerful whenever you want. Because Python is Turing complete , you can (in principle) compute anything that can be computed. You only need a powerful enough computer, a clever enough implementation, or both.

In this book, we implement each new mathematical concept in reusable Python code. Working through the implementation yourself can be a great way of cementing your understanding of a new concept, and by the end, you’ve added a new tool to your toolbelt. After trying it yourself, you can always swap in a polished, mainstream library if you like. Either way, the new tools you build or import lay the groundwork to explore even bigger ideas.

1.3.3 Building abstractions with functions

In programming, the process I just described is called abstraction. For example, when you get tired of repeated counting, you create the abstraction of addition. When you get tired of doing repeated addition, you create the abstraction of multiplication, and so on.

Of all the ways that you can make abstractions in programming, the most important one to carry over to math is the function. A function in Python is a way of repeating some task that can take one or more inputs or that can produce an output. For example,

def greet(name):
    print("Hello %s!" % name)

allows me to issue multiple greetings with short, expressive code like this:

>>> for name in ["John","Paul","George","Ringo"]:
...     greet(name)
...
Hello John!
Hello Paul!
Hello George!
Hello Ringo!

This function can be useful, but it’s not like a mathematical function. Mathematical functions always take input values, and they always return output values with no side effects.

In programming, we call the functions that behave like mathematical functions pure functions . For example, the square function f(x) = x2 takes a number and returns the product of the number with itself. When you evaluate f(3), the result is 9. That doesn’t mean that the number 3 has now changed and becomes 9. Rather, it means 9 is the corresponding output for the input 3 for the function f . You can picture this squaring function as a machine that takes numbers in an input slot and produces results (numbers) in its output slot (figure 1.16).

Figure 1.16 A function as a machine with an input slot and an output slot

This is a simple and useful mental model, and I’ll return to it throughout the book. One of the things I like most about it is that you can picture a function as an object in and of itself. In math, as in Python, functions are data that you can manipulate independently and even pass to other functions.

Math can be intimidating because it is abstract. Remember, as in any well-written software, the abstraction is introduced for a reason: it helps you organize and communicate bigger and more powerful ideas. When you grasp these ideas and translate them into code, you’ll open up some exciting possibilities.

If you didn’t already, I hope you now believe there are many exciting applications of math in software development. As a programmer, you already have the right mindset and tools to learn some new mathematical ideas. The ideas in this book provided me with professional and personal enrichment, and I hope they will for you as well. Let’s get started!

Summary

  • There are interesting and lucrative applications of math in many software engineering domains.

  • Math can help you quantify a trend for data that changes over time, for instance, to predict the movement of a stock price.

  • Different types of functions convey different kinds of qualitative behavior. For instance, an exponential depreciation function means that a car loses a percentage of its resale value with each mile driven rather than a fixed amount.

  • Tuples of numbers (called vectors) represent multidimensional data. Specifically, 3D vectors are triples of numbers and can represent points in space. You can build complex 3D graphics by assembling triangles specified by vectors.

  • Calculus is the mathematical study of continuous change, and many of the laws of physics are written in terms of calculus equations that are called differential equations.

  • It’s hard to learn math from traditional textbooks! You learn math by exploration, not as a straightforward march through definitions and theorems.

  • As a programmer, you’ve already trained yourself to think and communicate precisely; this skill will help you learn math as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109