Python can be used just like a pocket calculator. In addition to addition, subtraction, multiplication and division, you can calculate exponents and logarithms with Python. Exponent and logarithm functions are imported from the math module which is part of the Python Standard Library. This means all the functions in the math module are available in any Python installation.
In this short post, you'll learn how to calculate exponents and logarithms in Python.
Exponent and Logarithm Functions¶
The following exponent and logarithm functions can be imported from Python's math module:
log
log10
exp
e
pow(x,y)
sqrt
Let's try a couple of examples. In the examples below, the >>>
prompt is not meant to be typed. >>>
is used to denote the Python REPL or Python prompt. Alternatively, you can enter these examples into a Jupyter notebook code cell. Note how the first line of code imports logarithm and power functions from Python's math
module.
>>> from math import log, log10, exp, e, pow, sqrt
>>> log(3.0*e**3.4) # note: natural log
4.4986122886681095
Now let's try a problem: A right triangle has side lengths 3 and 4. What is the length of the hypotenuse?
>>> sqrt(3**2 + 4**2)
5.0
The power function pow()
works like the **
operator. pow()
raises a number to a power.
>>> 5**2
25
>>> pow(5,2)
25.0
Summary¶
The following exponent and logarithm functions are part of Python's math module:
Math function | Name | Description | Example | Result |
---|---|---|---|---|
math.e |
Euler's number | mathematical constant $e$ | math.e |
2.718 |
math.exp() |
exponent | $e$ raised to a power | math.exp(2.2) |
9.025 |
math.log() |
natural logarithm | log base $e$ | math.log(3.1) |
400 |
math.log10() |
base 10 logarithm | log base 10 | math.log10(100) |
2.0 |
math.pow() |
power | raises a number to a power | math.pow(2,3) |
8.0 |
math.sqrt() |
square root | square root of a number | math.sqrt(16) |
4.0 |
Support
Want to learn more about doing math with Python? Check out my book Problem Solving with Python on Amazon (Affiliate Link):