The Wayback Machine - https://web.archive.org/web/20241009152551/https://www.geeksforgeeks.org/log-functions-python/
Open In App

Log functions in Python

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python offers many inbuilt logarithmic functions under the module “math” which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article.
1. log(a,(Base)) : This function is used to compute the natural logarithm (Base e) of a. If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base).
 

Syntax :
math.log(a,Base)
Parameters :
a : The numeric value
Base : Base to which the logarithm has to be computed.
Return Value :
Returns natural log if 1 argument is passed and log with
specified base if 2 arguments are passed.
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of
# log(a,Base)

import math

# Printing the log base e of 14
print ("Natural logarithm of 14 is : ", end="")
print (math.log(14))

# Printing the log base 5 of 14
print ("Logarithm base 5 of 14 is : ", end="")
print (math.log(14,5))

Output : 

Natural logarithm of 14 is : 2.6390573296152584
Logarithm base 5 of 14 is : 1.6397385131955606


2. log2(a) : This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2).

Syntax :
math.log2(a)
Parameters :
a : The numeric value
Return Value :
Returns logarithm base 2 of a
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of
# log2(a)

import math

# Printing the log base 2 of 14
print ("Logarithm base 2 of 14 is : ", end="")
print (math.log2(14))

Output : 

Logarithm base 2 of 14 is : 3.807354922057604


3. log10(a) : This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10).

Syntax :
math.log10(a)
Parameters :
a : The numeric value
Return Value :
Returns logarithm base 10 of a
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of
# log10(a)

import math

# Printing the log base 10 of 14
print ("Logarithm base 10 of 14 is : ", end="")
print (math.log10(14))

Output : 

Logarithm base 10 of 14 is : 1.146128035678238


3. log1p(a) : This function is used to compute logarithm(1+a) . 

Syntax :
math.log1p(a)
Parameters :
a : The numeric value
Return Value :
Returns log(1+a)
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of
# log1p(a)

import math

# Printing the log(1+a) of 14
print ("Logarithm(1+a) value of 14 is : ", end="")
print (math.log1p(14))

Output : 

Logarithm(1+a) value of 14 is : 2.70805020110221
Exception


1. ValueError : This function returns value error if number is negative. 

Python3
# Python code to demonstrate the Exception of
# log(a)

import math

# Printing the log(a) of -14
# Throws Exception
print ("log(a) value of -14 is : ", end="")
print (math.log(-14))

Output : 

log(a) value of -14 is : 

Runtime Error : 

Traceback (most recent call last):
File "/home/8a74e9d7e5adfdb902ab15712cbaafe2.py", line 9, in
print (math.log(-14))
ValueError: math domain error
Practical Application


One of the application of log10() function is that it is used to compute the no. of digits of a number. Code below illustrates the same.

Python3
# Python code to demonstrate the Application of
# log10(a)

import math

# Printing no. of  digits in 73293
print ("The number of digits in 73293 are : ", end="")
print (int(math.log10(73293) + 1))

Output : 

The number of digits in 73293 are : 5

The natural logarithm (log) is an important mathematical function in Python that is frequently used in scientific computing, data analysis, and machine learning applications. Here are some advantages, disadvantages, important points, and reference books related to log functions in Python:

Advantages:

The log function is useful for transforming data that has a wide range of values or a non-normal distribution into a more normally distributed form, which can improve the accuracy of statistical analyses and machine learning models.
The log function is widely used in finance and economics to calculate compound interest, present values, and other financial metrics.
The log function can be used to reduce the effect of outliers on statistical analyses by compressing the scale of the data.
The log function can be used to visualize data with a large dynamic range or with values close to zero.

Disadvantages:

The log function can be computationally expensive for large datasets, especially if the log function is applied repeatedly.
The log function may not be appropriate for all types of data, such as categorical data or data with a bounded range.

Important points:

  1. The natural logarithm (log) is calculated using the numpy.log() function in Python.
  2. The logarithm with a base other than e can be calculated using the numpy.log10() or numpy.log2() functions in Python.
  3. The inverse of the natural logarithm is the exponential function, which can be calculated using the numpy.exp() function in Python.
  4. When using logarithms for statistical analyses or machine learning, it is important to remember to transform the data back to its original scale after analysis.

Reference books:

“Python for Data Analysis” by Wes McKinney covers the NumPy library and its applications in data analysis in depth, including the logarithmic function.
“Numerical Python: A Practical Techniques Approach for Industry” by Robert Johansson covers the NumPy library and its applications in numerical computing and scientific computing in depth, including the logarithmic function.
“Python Data Science Handbook” by Jake VanderPlas covers the NumPy library and its applications in data science in depth, including the logarithmic function.

Log functions in Python – FAQs

What is the Log Function in Python?

The logarithmic function in Python can be accessed through the math module for natural logarithms and logarithms of any base. The math.log() function returns the natural logarithm (base e) of a number, while math.log(x, base) returns the logarithm of x to the specified base.

Example using math.log:

import math

# Natural logarithm
print(math.log(2.7183)) # Output close to 1

# Logarithm base 10
print(math.log(100, 10)) # Output close to 2

What is the log2 Function in Python?

The log2 function specifically calculates the logarithm base 2 of a number and is also found in the math module. It’s useful in contexts where logarithms with base 2 are needed, such as in computer science for calculations involving binary systems.

Example of using math.log2:

import math

# Logarithm base 2
print(math.log2(32)) # Output: 5

How to Do log 10 in Python?

To calculate the base 10 logarithm in Python, you can use the math.log10() function, which is optimized for base 10 calculations and can be more precise than using math.log(x, 10).

Example:

import math

# Logarithm base 10
print(math.log10(1000)) # Output: 3

What is Login Function in Python?

In Python, a login function would generally be a custom function designed to handle user authentication. This function might interact with a user database or another authentication service to check user credentials. Python itself doesn’t have a built-in “login” function; such functionality needs to be implemented according to specific application requirements.

Example of a simple login function:

def login(username, password):
# This is a placeholder for actual authentication logic
if username == "admin" and password == "secret":
return "Logged in successfully."
else:
return "Invalid credentials."

# Usage
print(login("admin", "secret"))

What is the Log Function in Numpy?

Numpy, a library for numerical operations in Python, provides its own set of logarithmic functions, which are vectorized and capable of operating on arrays. The numpy.log() function calculates the natural logarithm of each element in an input array.

Example using numpy.log:

import numpy as np

data = np.array([1, np.e, np.e**2, 10])
print(np.log(data)) # Output will be the natural log of each element

Numpy’s log functions are useful for scientific and engineering applications where calculations often involve large datasets or arrays. These functions can handle arrays efficiently, unlike the math module functions, which only operate on single numbers.



Similar Reads

Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Python | cmath.log() method
With the help of cmath.log() method, we can find the value of log of any number having natural base value by passing it to cmath.log() method. Syntax : cmath.log(value) Return : Return the log value of natural base. Example #1 : In this example we can see that by using cmath.log() method, we are able to get the values of log having natural base by
1 min read
Python - Log Normal Distribution in Statistics
scipy.stats.lognorm() is a log-Normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Default = 0 scal
2 min read
Python - Log Laplace Distribution in Statistics
scipy.stats.loglaplace() is a log-Laplace continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Default = 0
2 min read
Python - Log Gamma Distribution in Statistics
scipy.stats.loggamma() is a log gamma continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Default = 0 scal
2 min read
Python - Power Log-Normal Distribution in Statistics
scipy.stats.powerlognorm() is a power log-normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Defau
2 min read
Log transformation of an image using Python and OpenCV
Logarithm value of a number is a number that raises power to a base number which gives the same number as in input. Simply, the logarithm is the inversion of exponential value of a number. log(exp(x)) = x How log value of a number is calculated? Let's see an example, [Tex]2^3 = 8[/Tex] By applying logarithm in both sides, log(2^3) = log(8) 3 * log(
3 min read
Python - PyTorch log() method
PyTorch torch.log() method gives a new tensor having the natural logarithm of the elements of input tensor. Syntax: torch.log(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept with the help of few examples: Example 1: # Importing the PyTorch library import torch # A c
1 min read
Python - tensorflow.raw_ops.Log()
TensorFlow is open-source python library designed by Google to develop Machine Learning models and deep learning neural networks. TensorFlow raw_ops provides low level access to all TensorFlow operations. Log() is used to find element wise logarithm of x. Syntax: tf.raw_ops.Log(x, name) Parameters: x: It's the input tensor. Allowed dtype for this t
2 min read
sympy.log() method in Python
With the help of sympy.log() function, we can simplify the principal branch of the natural logarithm. Logarithms are taken with the natural base, e. To get a logarithm of a different base b, use log(x, y), which is essentially short-hand for log(x) / log(y). Syntax : sympy.log() Return : Return the simplified mathematical expression. Example #1 : C
1 min read
How to make Log Plots in Plotly - Python?
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. What are the log plots? A log plot is a way of
2 min read
How to Log Queries in PostgreSQL using Python?
Python has various database drivers for PostgreSQL. Current most used version is psycopg2. It fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc. Installation Install the psycopg2 module :
4 min read
How to generate random numbers from a log-normal distribution in Python ?
A continuous probability distribution of a random variable whose logarithm is usually distributed is known as a log-normal (or lognormal) distribution in probability theory. A variable x is said to follow a log-normal distribution if and only if the log(x) follows a normal distribution. The PDF is defined as follows. Where mu is the population mean
3 min read
Python Script to Monitor Network Connection and saving into Log File
In this article, we are going to see how to monitor the network connection and save the log file in Python. The basic ideology of this script is to give real-time information about if the system the script is being run on is connected to an internet connection or not, and save that information into a log file simultaneously, keeping records of when
8 min read
Log and natural Logarithmic value of a column in Pandas - Python
This article explores the computation of logarithmic and natural logarithmic values for a column in Pandas using Python. What is Log and Natural Logarithmic?A logarithm is a mathematical function that represents the exponent to which a base must be raised to produce a given number. The logarithm of a number x to the base b is denoted as log_b(x), a
4 min read
How to log a Python exception?
To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an error can be done in the logging.exception() meth
2 min read
numpy.log() in Python
The numpy.log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements. Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm is log in base e. Syntax :numpy.log(x[, out] = ufunc 'log1p') Parameters : array : [array_like] Input array
4 min read
How To Use Python To Parse Server Log Files
Server log files are an invaluable source of information for system administrators and developers. They contain records of various events and activities that occur on a server, such as requests, errors, warnings, and more. Parsing these log files can provide insights into system performance, security issues, and user behavior. What is Parsing Serve
4 min read
How to Log Python Messages to Both stdout and Files
Python Loggers are essential tools for tracking and debugging applications, allowing developers to record messages of various severity levels. By configuring loggers to output messages to both stdout and log files, developers can ensure real-time monitoring and persistent storage of logs for later analysis. In this article, we will explore two diff
2 min read
How to log all sql queries in Django?
Django, a popular web framework for Python, simplifies the development of database-driven applications. When building Django applications, it's crucial to monitor and optimize the SQL queries executed by your application for performance and debugging purposes. One effective way to achieve this is by logging all SQL queries. In this article, we will
4 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Array in Python | Set 2 (Important Functions)
Array in Python | Set 1 (Introduction and Functions)Array in Python | Set 2Below are some more useful functions provided in Python for arrays: Array Typecode FunctionThis function returns the data type by which the array is initialized. In this example, we are using arr.typecode to find out the data type of array initialization. C/C++ Code # import
3 min read
Bisect Algorithm Functions in Python
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module "bisect" which allows keeping the list in sorted order after the insertion of each element. This is essential as this reduces overhead time required to
5 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | startswith() and endswith() functions
Python library provides a number of built-in methods, one such being startswith() and endswith() functions which are used in string related operations. Startswith() Syntax: str.startswith(search_string, start, end) Parameters : search_string : The string to be searched. start : start index of the str from where the search_string is to be searched.
2 min read
maketrans() and translate() functions in Python
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article. maketrans() maketrans() function is used to construct the transition table i.e specify the
3 min read
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them
3 min read
Article Tags :
Practice Tags :