NumPy Logs

M.Ramya

 Logs in NumPy

NumPy provides built-in functions to compute logarithms with bases 2, e (natural log), and 10. Additionally, you can create a custom function to compute logarithms with any base.

Note: If the logarithm cannot be computed for certain elements, NumPy will return -inf or inf.



Logarithm with Base 2

Use the np.log2() function to compute the base-2 logarithm of array elements.

Program:

import numpy as np
arr = np.arange(1, 10)  # Creates an array from 1 to 9
print(np.log2(arr))

Output:

[0.         1.         1.5849625  2.         2.32192809 2.5849625
 2.80735492 3.         3.169925   ]

Logarithm with Base 10

Use the np.log10() function for base-10 logarithms.

Program:

import numpy as np
arr = np.arange(1, 10)
print(np.log10(arr))

Output:

[0.         0.30103    0.47712125 0.60205999 0.69897    0.77815125
 0.84509804 0.90308999 0.95424251]

Natural Logarithm (Base e)

For natural logarithms (base e), use np.log().

Program:

import numpy as np
arr = np.arange(1, 10)
print(np.log(arr))

Output:

[0.         0.69314718 1.09861229 1.38629436 1.60943791 1.79175947
 1.94591015 2.07944154 2.19722458]

Logarithm with Any Base

NumPy doesn’t provide a direct function for arbitrary bases. However, you can use np.frompyfunc() along with Python’s built-in math.log() to create a custom universal function (ufunc).

Program:

from math import log

import numpy as np
nplog = np.frompyfunc(log, 2, 1)  # 2 inputs (value and base), 1 output
print(nplog(100, 15))  # Log of 100 with base 15

Output:

1.7005483074552052
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send