Jump Links
-
Logarithmic and Exponential Functions
It’s a common joke that Python makes a great calculator in its interactive mode. You can make it an even better one with the built-in math module, which contains a lot of the same math functions you would find on a handheld scientific or graphing calculator.
Constants
One useful feature of the Python math module is quick access to mathematical constants. You can make Python more effective as a scientific calculator by using these same functions with numerical approximations. The most famous might be pi (3.14159, etc.). You don’t have to remember all the digits. Python will do it for you.
Let’s call up pi to calculate the area of a circle. Suppose we had a 12-inch pizza and wanted to know how much pizza we actually got in terms of area.
First, we’ll import the math library:
import math
We’ll store the radius in a variable. The radius is half of the diameter of a circle, so a 12-inch pizza has a 6-inch radius.
radius = 6
The formula for the area of a circle is pi times the square of the radius. In Python, that would be:
area_circ = math.pi * radius**2
The double-asterisk is how you represent exponents in Python.
The result is that a round 12-inch pizza has about 113 square inches of actual pizza in it. This is why you should order a bigger pizza, according to NPR.
Another common constant you can use with Python is e, or 2.718281828459045. This is the base of the natural logarithm and is commonly used for exponential growth, such as compound interest.
Suppose you want to invest $5,000 compounded continuously at an interest rate of two percent over 5 years. The formula is the principal multiplied by e raised to the interest rate multiplied by the time.
Here it is in Python:
principal = 5000
rate = .02
time = 5
compound_interest = principal * math.e**(rate * time)
compound_interest
You would have approximately $5,525 at the end of five years. These math functions shine in interactive modes, which is one reason Python can replace your calculator app. If you’re using these functions in a script, you’ll need a print statement, such as:
print(math.pi)
You don’t need to do this in interactive mode, as you can just type a statement at the prompt to get its value. This is what the rest of this article will assume you’re doing for simplicity.
Trigonometric Functions
Trigonometric functions are a major use for scientific calculators. They’re easy to do with the math library. The trigonometric functions expect radians instead of degrees, which you might be more familiar with, but it’s easy to convert between the two using the built-in radians and degrees functions.
Let’s convert 45 degrees into radians:
math.radians(45)
The result is 0.7853981633974483
In an interactive session, we can convert that back into degrees using the _ (underscore) character, which holds the value of the last properly evaluated result.
math.degrees(_)
This will give us back 45.
Let’s store our radian measure in a variable called “theta,” the Greek variable that’s commonly used to represent angle measures in radians.
theta = math.radians(45)
Let’s take the sine:
math.sin(theta)
We can take the cosine as well
math.cos(theta)
And the tangent:
math.tan(theta)
You can get back the original values with the inverse values or arc values. For example, to calculate the arcsine:
sine = math.sine(theta)
math.asin(sine)
Compare the arcsine to the original value of the angle. We can do the same with the other trigonometric ratios and their inverse functions.
cosine = math.cos(theta)
math.acos(cosine)tangent = math.tan(theta)
math.atan(tangent)
Logarithmic and Exponential Functions
Operations dealing with exponents and logarithms are another major part of math.
As seen earlier, the double asterisk (**) raises a number to a power.
2**2
9**2
You can also use the pow function to raise a number to a power. tFor example, to square the number 9:
math.pow(9,2)
This will give the answer 81
To get the inverse, you can use a logarithm. The log function by default uses e as a base, the constant we saw earlier. It’s also known as the Napierian logarithm, after John Napier, who discovered the logarithm.
Let’s raise e to the 5th power.
math.e**5
This will give us 148.41315910257657
We can reverse this with the log function:
math.log(148.41315910257657)
This will get us back to 5.
This will also work with other bases.
9**2
math.log(81,9)
A good way to find out how many bits are needed to store a number is to use a logarithm with base 2:
math.log(2048,2)
This will give us 11. There’s also a log2 function as a shortcut:
math.log2(2048)
There’s also a shortcut for the common logarithm or Briggsian logarithm, named after Henry Briggs, who popularized the logarithm with base 10. Before calculators were widely available, tables of these logarithms were published in books to speed up multiplication and division. You would find tables of both natural and common logarithms in the back of old math textbooks and as standalone volumes. They took advantage of a property of logarithms that addition and subtraction of logarithms is the same as the multiplication and division of these numbers (slide rules also worked on this principle).
Let’s multiply 23 and 42 using logarithms
math.log10(23) + math.log10(42)
To find the product, raise 10 to the power of the sum of the two logarithms.
10**_
This also works for natural logarithms:
math.log(23) + math.log(42)
math.e**_
The property also works for subtraction:
math.log10(966) - math.log10(42)
This will give us 23. As greatly as logarithms simplified multiplication and division, the advent of calculators simplified them even further, making logarithms largely obsolete for most nonscientists. They’re still useful in some areas, such as dealing with exponential functions and making them appear linear so that linear regression can be applied on them.
Numeric Calculations
There are other various numeric calculations you can perform with the Python math module.
You can take the square root of a number with the sqrt function:
math.sqrt(81)
That, of course, will give you 9. You can also take a cube root of a number with cbrt:
math.cbrt(81)
This will give us a decimal approximation of 4.326748710922225.
The pow function will raise a number to a power, similar to the ** operator.
math.pow(3,2)
This will square 3 to give 9. You can also take nth roots by raising a power to a fractional amount.
math.pow(3,1/2)
This will also have the effect of squaring 3. This property is useful for taking roots higher than 3. To take the 8th root of 1024.
math.pow(1024,1/8)
This gives another decimal approximation. If you want an exact answer, you’ll need a computer algebra system like the SymPy library.
Some other useful functions are the ceiling and floor functions. The ceiling function will round a number up to the nearest integer, while the floor will round it to the lowest integer.
math.ceiling(42.5)
This will return 43. Let’s try this on the floor:
math.floor(42.5)
This will return 42.
This is similar to the // (double slash) operator built into Python that will perform floor division, without a remainder (and which also used to be the default division behavior in Python).
The remainder function will also return the remainder of its arguments.
For example, to return the remainder of 5 divided by 4:
math.remainder(5,4)
To remove a decimal part completely, use the trunc function.
math.trunc(42.5)
This will return 42.
Sums and Products
To return the sum of the elements in an array or tuple, use the fsum function:
math.fsum([2.5,4,5])
This gives 11.5.
To take the product of the numbers in a tuple or array, use the prod function:
math.prod([2.5,4,5]
This will return 50.
Combinatorial Functions
Combinatorial functions are useful for counting things quickly, and are common in probability theory and discrete math.
A factorial, represented by an exclamation point (!) is a number * that number minus 1, times that number subtracted by 1. The factorial of 0 is 1.
For example, 5 factorial or 5! is 5 * 4 * 3 * 2 * 1.
To calculate 5!, use the factorial function:
math.factorial(5)
Permutations are a way of counting combinations when a certain order is required. Suppose you wanted to arrange eight books on a shelf in a certain order of three books. You would use the perm function:
math.perm(8,3)
This will give 336.
Combinations are similar but are used when order doesn’t matter. To count the ways you can draw 5 cards from a well-shuffled 52-card deck, you can use the comb function
math.comb(52,5)
This gives over 2 million possible combinations of cards, which is a lot of ways to lose at poker.
The Python math library has lots of functions to make your calculations easier and more fun. It’s not surprising the language is popular, even as a souped-up calculator.