Python log() Functions to Calculate Logarithm

In this tutorial, there will be a discussion about log() functions to compute logarithms. The Python log() function takes a number as an argument and returns the log of that number. The logarithm is the exponent to which other base number needs to be raised to create the given number. In this article, you will learn about some useful tools like numpy, math, tensorflow, and log library functions that allow us to easily calculate logarithms to solve probability-related problems, analyze data, and classify data. 

*working on Jupyter Notebook Anaconda Prompt Python version 3.0+. 

Purpose of using logarithm 

Numbers are generally large when it comes to economic value or income level. Using the log, large numbers are de-scaled for computing. Calculated or modeled results can be scaled back to their original dimensions once they have been computed or modeled. 

Moreover, it may be useful in a variety of mathematical applications, including finance, physics, and engineering, where exponential growth and decay are commonly observed. Moreover, Logarithmic loss functions, also known as cross-entropy loss functions, are also commonly used to predict probability values for classification problems.

What does the log () function do?

Python’s log() function is available in the math module. It takes one or two arguments, where the first argument is the number whose logarithm is to be calculated. The second argument is the logarithm base, which is optional. If the base is not provided, the function assumes a base of e (natural logarithm).

The log() function is commonly used in various applications, such as calculating growth rates, computing probabilities, analyzing data, and more.

How does math.log work?

Using math.log, one can calculate the natural logarithm at the base e. However, to compute the natural logarithm at the base 10, you can use math.log10.

For example, math.log(2) returns the natural logarithm of 2, which is approximately equal to 0.693147. Similarly, math.log(2, 5) returns the base-5 logarithm of 2, which is approximately equal to 0.43067.

import math
import matplotlib.pyplot as plt
# Define the range of values
x = range(1, 101)
# construct an empty list to store the logarithmic values
y = []
for i in x:
   y.append(np.math.log(i))
# Plot the graph of the logarithmic values
plt.plot(x, y)
#express label
plt.xlabel('x')
plt.ylabel('log(x)')
plt.title('Logarithmic Graph from 0 to 100')
plt.show()

Python log() Functions to Calculate Logarithm

Logarithm of uses two basic log() functions when dealing with math module when computing logarithm.

math.log() 

The natural logarithm with base e, if the base is not provided, the math module considers it equal to e(Euler’s number) 

math.log10()

The math module takes two arguments if the second argument has specific base. To handle natural logarithm at base 10 use log base 10 math.log10(). 

Logarithm Function with Base-2

To compute the log base 2, follow the following straightforward procedure to calculate the natural logarithm. 

  • First, you have to import the math library, which handles mathematical functions, including the log() function.
  • Then invoke log() function with a single argument, 3.1, as discussed in the above sections it will calculate the natural logarithm (base e) of 3.1.
  • Lastly, store the result of the log() function in the variable log_base_e.
# importing math library
import math
# using natural log method
log_base_e = math.log(3.1)
print(log_base_e)
1.1314021114911006

Logarithm Function with Base-10

For calculating log base 10, utilize the following straightforward method. 

  • Consider importing the math library, which handles the log() functions.
  • Then call log10() function with a single argument, 3.1, as discussed in the above sections it will compute the natural logarithm with the base 10 of 3.1.
  • Lastly, store the result of the log10() function in the variable log_10_base.
# importing math library
import math
# using log base 10 method
base_10_log= math.log10(3.1)
print(base_10_log)
0.4913616938342727

graphical preview OF Logarithm Function with Base-10 and Base-2

Above is a demonstration how math modules handle base 10 or base e (natural logarithm) programmatically. Here in this section there will be a discussion how both behave in a graphical perspective. 

Taking a look at the plot, we can see that the natural logarithm function (orange line) grows more rapidly for higher values of x than the base 10 logarithm function (blue line). This is because the natural logarithm function is a more slowly increasing function than the base 10 logarithm function.

Additionally, we can see that the base 10 logarithm function has a horizontal asymptote at y = 0, while the natural logarithm function approaches negative infinity as x approaches zero. 

This is because the base 10 logarithm function approaches zero as the input approaches zero, while the natural logarithm function approaches negative infinity because the natural logarithm of any value less than or equal to zero is undefined.

#import numpy library to deal mathematical problems
import numpy as np
#import library to support plot
import matplotlib.pyplot as plt
# construct the range of x values
x = np.linspace(0, 5, 10)
# using log base 10 and natural logarithm methods to plot and compare their behavior
base_10_log = np.log10(x)
log_base_e = np.log(x)
# Plot the natural log and base 10 log functions
plt.plot(x, base_10_log, label='log base 10')
plt.plot(x, log_base_e, label='natural logarithm')
# Set the plot title and labels for the x and y axes
plt.title('log base 10 and natural logarithm functions behaviour')
plt.xlabel('x')
plt.ylabel('y')
# Show the legend and plot
plt.legend()
plt.show()

logarithm Function output without using math log python

The below example code defines two functions, log() and ln(), and uses them to calculate the logarithm of a given number x with respect to a given base without a math module.

  • The ln() function computes (e) the natural logarithm of a number x. It does so by using a mathematical approximation that involves raising x to the power of a very large number and subtracting 1 from the result. The function returns this value as the natural logarithm of x.
  • The log() function takes two arguments, x and base, and calculates the logarithm of x with respect to the given base. The function then returns this value as the logarithm of x with respect to the given base, when the log() function invokes the arguments 3.14 and 10, which calculates the base-10 logarithm of 3.14. 
def log(x,base):
   result = ln(x)/ln(base)
   return result
def ln(x):
   val = x
   return 99999999*(x**(1/99999999)-1)
log(3.14,10)
0.49692964891846436

Overall, the above example uses a mathematical approximation without using math module to calculate the natural logarithm of a given number.

NumPy Logarithm function with Base-2

Using the NumPy library to calculate the base-2 logarithm of an array of integers.

The procedure is straightforward. Here’s how it executes:

  • Import numpy library with the shorthand nump
  • The nump.array() function creates an array of integers with the log values [0, 1, 2, 5].
  • The nump.log2() function is then used to calculate the base-2 logarithm of each value in the array created in the above command line.
  • The value is stored in a defined variable arr and prints the log array values with respect to the integer.
import numpy as nump
# create the log value of an array with base 2
arra = nump.array([0,1,2,5])
arr = nump.log2(arra)
print(arr)
[      -inf 0.         1.         2.32192809]

The output of the program is the array [-inf, 0, 1, 2.32192809], which represents the base-2 logarithm of each integer value in the input array. However, The first value in the output array is -inf, which represents the logarithm of 0. This is because the logarithm of 0 is undefined in mathematics.

NumPy Logarithm function with Base-10

The procedure is the same as demonstrated in the above example code. Using the NumPy library you can compute the base-10 logarithm of each value in an array of integers.

import numpy as np
# get the log value of an array with base 2
arra = np.array([0,1,2,5])
arr = np.log10(arra)
print(arr)
[   -inf 0.      0.30103 0.69897]

The output of the program is the array [   -inf 0.      0.30103 0.69897], which represents the base-10 logarithm of each integer value in the input array. However, The first value in the output array is -inf, which represents the logarithm of 0. This is because the logarithm of 0 is undefined in mathematics.

graphical preview of NumPy Logarithm with Base-10 and Base-2

Taking a look at the plot, It shows the behavior of the natural logarithm and base 10 logarithm functions for an array of values from 0 to 5. The blue line represents the base 10 logarithm function and the red line represents the natural logarithm function.

For the natural logarithm function, the behavior indicates that the natural logarithm of a larger number or higher value of x, grows much faster than that of a smaller number (lower value of x). 

For the base 10 logarithm function, the base is 10, the y-values increase faster than the natural logarithm function for larger values of x.

import matplotlib.pyplot as plt
arra = np.array([0,1,2,5])
log_base_e = np.log2(arra)
base_10_log = np.log10(arra)
# Plot the natural log and base 10 log functions
plt.plot(arra, base_10_log, label='log base 10',marker='*', color='blue')
plt.plot(arra, log_base_e, label='natural logarithm',marker='o', color='red')
# Set the plot title and labels for the x and y axes
plt.title('log base 10 and natural logarithm array functions behaviour')
plt.xlabel('x')
plt.ylabel('y')
# Show the legend and plot
plt.legend()
plt.show()

logarithm Function with math log python

Using the math module, one can calculate the complex algorithms or analyze data on a logarithmic scale.

Here ‘s how it executes:

  • Consider importing the math module in Python to compute the logarithm of 8 with base 2 and base 10.
  • The function math.log2(8) calculates the logarithm of 8 with base 2, which is equal to 3.0. This means that 2 raised to the power of 3 gives us the value of 8.
  • Same is the case with the logarithm of 8 with base 10.
# construct natural log --> log2(a)
import math
# constructing the log base 2 of 8
print ("Logarithm base 2 of 8 is : ")
print (math.log2(8))
print('\n')
# constructing the log base 10 of 8
print ("Logarithm base 10 of 8 is : ")
print (math.log10(8))
Logarithm base 2 of 8 is : 
3.0


Logarithm base 10 of 8 is : 
0.9030899869919435

Tensorflow log() method

Performing logarithmic computations on tensors in the TensorFlow environment has a wide range of applications in machine learning and data analysis. Before moving towards calculating the log() functions using tensorflow, you need to fix important attribute errors first. 

AttributeError: module ‘tensorflow’ has no attribute ‘log’ 

Instead of Importing the simple Tensorflow library and if you are working on tensorflow version above 2.0, then it will raised the attribute error:module ‘tensorflow’ has no attribute ‘log’ 

“ To resolve and fix then AttributeError: module ‘tensorflow’ has no attribute ‘log’, use the tensorflow.compat.v1 and disable_v2_behavior() library to start your code functioning. 

The below example code demonstrates the usage of TensorFlow’s tf.log() method to calculate the natural logarithm of an input array Input, and then plots the input and output values using matplotlib.pyplot.

Here’s how it executes:

The procedure is straightforward:

  • Note here that Session instances uses to execute Operations in a Graph, when handling tensors.
  • Creates the input array Input using the NumPy library, where it consists of 13 data points from 0 to 5 and another 13 data points from 1 to 5.
  • The tf.log() method takes the Input array as its input and computes the natural logarithm of each element of the array.
  • Start executing TensorFlow session for the computational graph and calculate the values of Output. 
  • The plotted graph shows how the method works to compute the natural logarithm of an input array.

In the plotted graph, the x-axis represents the values in the input array Input, while the y-axis represents the corresponding natural logarithmic values computed using tf.log(). 

As you move from left to right on the x-axis on a plotted graph, the values of the elements in Input increase, and as a result, the values on the y-axis also increase. The plotted graph shows an exponentially increasing logarithmic curve with a linear input.

# instead of Importing the Tensorflow library if you have tensorflow version above 2.0
#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
print('tensorflow version: \n' , tf.__version__)
from tensorflow import keras
# Import the NumPy library to handle mathematical problems
import numpy as nump
# Import the matplotlib.pyplot function for graphical view
import matplotlib.pyplot as plt
#input array consists of 13 data points
Input = nump.append(np.linspace(0, 5, 13), np.linspace(1, 5, 13))
# Applying the logarithmic function and storing the result in 'b'
Output = tf.log(Input, name ='log')
# atRTING a Tensorflow session
with tf.Session() as sess:
   print('Input: \n', Input)
   print('Output: \n', sess.run(Output))
   plt.plot(Input, sess.run(Output), color = 'blue', marker = "*")
#label and title
   plt.title("tensorflow.abs")
   plt.xlabel("X")
   plt.ylabel("Y")
#to display graphical view
   plt.show()
tensorflow version: 
 2.12.0
Input: 
 [0.         0.41666667 0.83333333 1.25       1.66666667 2.08333333
 2.5        2.91666667 3.33333333 3.75       4.16666667 4.58333333
 5.         1.         1.33333333 1.66666667 2.         2.33333333
 2.66666667 3.         3.33333333 3.66666667 4.         4.33333333
 4.66666667 5.        ]
Output: 
 [       -inf -0.87546874 -0.18232156  0.22314355  0.51082562  0.73396918
  0.91629073  1.07044141  1.2039728   1.32175584  1.42711636  1.52242654
  1.60943791  0.          0.28768207  0.51082562  0.69314718  0.84729786
  0.98082925  1.09861229  1.2039728   1.29928298  1.38629436  1.46633707
  1.54044504  1.60943791]

Conclusion

The article covers most of the prevalent ways to deal and compute logarithms in Python in a more straightforward way. There methods includes:

  • How does math.log work?
  • Python log() Functions to Calculate Logarithm
  • Logarithm Function with Base-2
  • Logarithm Function with Base-10
  • graphical preview OF Logarithm Function with Base-10 and Base-2
  • Logarithm Function output without using math log python
  • NumPy Logarithm function with Base-2
  • NumPy Logarithm function with Base-10
  • graphical preview of NumPy Logarithm with Base-10 and Base-2
  • logarithm Function with math log python
  • Tensorflow log() method
    • AttributeError: module ‘tensorflow’ has no attribute ‘log’ 

Leave a Comment

Your email address will not be published. Required fields are marked *