This article will show you how to calculate natural logs/logarithms in the Python programming language, with examples.
What is a Natural Log/Logarithm (ln)?
A number’s natural logarithm is it’s logarithm to the base of e.
It’s a bit more advanced than the usual arithmetic you’re probably used to seeing as you learn to program, so here’s a bit of explanation:
A logarithm is the reverse of an exponent. The logarithm of a number is the exponent that another number must be raised to to produce the first number.
You’re probably familiar with squaring numbers, so consider the following:
32 = 9
3 squared, or raised to the power of 2 (noted by the exponent) equals 9 – relatively simple stuff. The inverse of this, the logarithm, would be:
log3(9) = 2
To get 9, 3 must be raised to the power of 2.
e is a mathematical constant which is important for use in a variety of applications.
Following from the above, the natural logarithm for a number would be represented as below, with e as the base:
loge(number) = ?
Natural logarithms are also called the natural log or are represented with the abbreviation ln.
Calculating Natural Logarithms in Python
Python includes the built in math.log() function for calculating natural logarithms. The syntax is as follows:
And it is used as such:
import math math.log(4)
Which will return the answer
…The natural log of 4.
Note that the math library must be imported first.
An optional base can also be supplied, which will then return the logarithm to the given number to the given base, rather than returning the natural logarithm.
import math math.log(9, 3)
Which will return the answer: