Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
The Statistics and Calculus with Python Workshop

You're reading from  The Statistics and Calculus with Python Workshop

Product type Book
Published in Aug 2020
Publisher Packt
ISBN-13 9781800209763
Pages 740 pages
Edition 1st Edition
Languages
Concepts
Authors (6):
Peter Farrell Peter Farrell
Profile icon Peter Farrell
Alvaro Fuentes Alvaro Fuentes
Profile icon Alvaro Fuentes
Ajinkya Sudhir Kolhe Ajinkya Sudhir Kolhe
Profile icon Ajinkya Sudhir Kolhe
Quan Nguyen Quan Nguyen
Profile icon Quan Nguyen
Alexander Joseph Sarver Alexander Joseph Sarver
Profile icon Alexander Joseph Sarver
Marios Tsatsos Marios Tsatsos
Profile icon Marios Tsatsos
View More author details

Table of Contents (14) Chapters

Preface
1. Fundamentals of Python 2. Python's Main Tools for Statistics 3. Python's Statistical Toolbox 4. Functions and Algebra with Python 5. More Mathematics with Python 6. Matrices and Markov Chains with Python 7. Doing Basic Statistics with Python 8. Foundational Probability Concepts and Their Applications 9. Intermediate Statistics with Python 10. Foundational Calculus with Python 11. More Calculus with Python 12. Intermediate Calculus with Python Appendix

10. Foundational Calculus with Python

Overview

In this chapter, you will learn to calculate the derivatives of functions at a given value of x. You'll also learn to calculate the integrals of functions between given values and use derivation to solve optimization problems, such as maximizing profit or minimizing cost. By the end of this chapter, you will be able to use calculus to solve a range of mathematical problems.

Introduction

Calculus has been called the science of change, since its tools were developed to deal with constantly changing values such as the position and velocity of planets and projectiles. Previously, there was no way to express this kind of change in a variable.

The first important topic in calculus is the derivative. This is the rate of change of a function at a given point. Straight lines follow a simple pattern known as the slope. This is the change in the y value (the rise) over a given range of x values (the run):

Figure 10.1: Slope of a line

In Figure 10.1, the y value in the line increases by 2 units for every 1-unit increase in the x value, so we divide 2 by 1 to get a slope of 2.

However, the slope of a curve isn't constant over the whole curve like it is in a line. So, as you can see in Figure 10.2, the rate of change of this function at point A is different from the rate of change at point B:

Figure 10.2: Finding...

Writing the Derivative Function

For all the fear whipped up about derivatives in calculus courses, the function for calculating a derivative numerically is surprisingly easy.

In a Jupyter notebook, we'll define a function, f(x), to be the parabola y = x2:

def f(x):
    return x**2

Now we can write a function to calculate the derivative at any point (x, f(x)) using the classic formula:

Figure 10.4: Formula for calculating derivatives

The numerator is the rise and the denominator is the run. Δ x means the change in x, and we're going to make that a really small decimal by dividing 1 by a million:

def f(x):
    return x**2
def derivative(f,x):
    """
    Returns the value of the derivative of
    the function at a given x-value.
    """
    delta_x = 1/1000000
 ...

Calculating Integrals

  1. One major topic of calculus is differential calculus, which means taking derivatives, as we've been doing so far in this chapter. The other major topic is integral calculus, which involves adding up areas or volumes using many small slices.

    When calculating integrals by hand, we're taught to reverse the algebra we would do to find a derivative. But that algebra gets messy and, in some cases, impossible. The hard version we learned in school was Riemann sums, which required us to cut the area under a curve into rectangular slices and add them up to get the area. But you could never work with more than 10 slices in a realistic amount of time, certainly not on a test.

    However, using Python, we can work with as many slices as we want, and it saves us the drudgery of jumping through a lot of hoops to get an algebraic equation. The point of finding the algebraic equation is to obtain accurate number values, and if using a program will get us the most accurate numbers...

Using Trapezoids

  1. We can get better approximations sooner using trapezoids rather than rectangles. That way, we won't miss as much area, as you can see in Figure 10.13:

    Figure 10.13: Using trapezoids for better approximations to the curve

    The following is the formula for the trapezoidal rule:

    Figure 10.14: Formula for area of trapezoids

    The heights of the segments at the endpoints x = a and x = b are counted once, while all the other heights are counted twice. That's because there are two heights in the formula for the area of a trapezoid. Can you guess how to adapt your integral function to be trapezoidal?

    def trap_integral(f,a,b,num):
        """Returns the sum of num trapezoids
        under f between a and b"""
        width = (b-a)/num
        area = 0.5*width*(f(a) + f(b) + 2*sum([f(a+width*n) for n in range(1,num)]))
        return area

    Now we'll run the trap_integral...

Using Integrals to Solve Applied Problems

If a curve is rotated about the x or y axis or a line parallel to one of the axes, to form a 3D object, we can calculate the volume of this solid by using the tools of integration. For example, let's say the parabola y = x2 is rotated around its axis of symmetry to form a paraboloid, as in Figure 10.16:

Figure 10.16: A parabola rotated about the z axis

We can find the volume by adding up all the slices of the paraboloid as you go up the solid. Just as before, when we were using rectangles in two dimensions, now we're using cylinders in three dimensions. In Figure 10.16, the slices are going up the figure and not to the right, so we can flip it in our heads and redefine the curve y = x2 as y = sqrt(x).

Now the radius of each cylinder is the y value, and let's say we're going from x = 0 to x = 1:

Figure 10.17: Flipping the paraboloid on its side

The endpoints are still 0...

Using Derivatives to Solve Optimization Problems

In many applied problems, we're looking for an optimal point, where the error is lowest, for example, or the profit is highest. The traditional way is to model the situation using a function, find the derivative of the function, and solve for the input that makes the derivative zero. This is because the derivative is zero at local minima and maxima, as shown in the following figure:

Figure 10.21: A cubic function and the points we want to find

The function we're given in the figure is f(x) = x3 - 2.8x2 + 1.2x + 0.85. We're interested in finding the local maximum, point A, and the local minimum, point B. We would have to differentiate the function and solve the resulting equation by hand. But using a computer, we can simply start at a value of x on the left of the grid and take small steps, checking f(x) until we get a change in direction. To do that, we can use our derivative function to check...

Summary

The tools of calculus allowed mathematicians and scientists to deal with constantly changing values, and those tools changed the way science is done. All of a sudden, we could use infinitely small steps to approximate the slope of a curve at a point, or infinitely small rectangles to approximate the area under a curve. These tools were developed hundreds of years before our modern world of computers and free programming software, but there's no reason to limit ourselves to the tools available to Newton, Leibniz, and the Bernoullis.

In this chapter, we learned to take derivatives of functions by simply dividing the rise of the function from one point to another by the infinitesimal run between those points. We simply told Python to divide 1 by a million to give us that small number. Without a computer, plugging those decimals into a function would be a daunting task, but Python plugs a decimal into a function as easily as a whole number.

We used the derivative idea...

lock icon The rest of the chapter is locked
You have been reading a chapter from
The Statistics and Calculus with Python Workshop
Published in: Aug 2020 Publisher: Packt ISBN-13: 9781800209763
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}