Home » Programming » Python » Python Natural Log

How to Calculate Natural Logs/Logarithms (ln) in Python

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:

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:

math.log(number)

And it is used as such:

import math

math.log(4)

Which will return the answer

1.3862943611198906

…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:

2
SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment