115

From the numpy documentation on logarithms, I have found functions to take the logarithm with base e, 2, and 10:

import numpy as np
np.log(np.e**3) #3.0
np.log2(2**3)   #3.0
np.log10(10**3) #3.0

However, how do I take the logarithm with base n (e.g. 42) in numpy?

cottontail
  • 10,268
  • 18
  • 50
  • 51
dwitvliet
  • 7,242
  • 7
  • 36
  • 62

2 Answers2

223

If you have numpy 1.23 or later, you can use np.emath.logn:

import numpy as np
array = np.array([74088, 3111696])  # = [42^3, 42^4]
base = 42
exponent = np.emath.logn(base, array)  # = [3, 4]

If your version of numpy is older:

To get the logarithm with a custom base using math.log:

import math
number = 74088  # = 42^3
base = 42
exponent = math.log(number, base)  # = 3

To get the logarithm with a custom base using numpy.log:

import numpy as np
array = np.array([74088, 3111696])  # = [42^3, 42^4]
base = 42
exponent = np.log(array) / np.log(base)  # = [3, 4]

Which uses the logarithm base change rule:

\log_b(x)=\log_c(x)/\log_c(b)

dwitvliet
  • 7,242
  • 7
  • 36
  • 62
  • 26
    I cant understand why base isn't a parameter in numpy's log... I'm always coming back here... – polvoazul Oct 21 '21 at 14:30
  • 10
    "When will I ever use this?" -Student – Tyler Pantuso Aug 23 '22 at 13:20
  • 2
    @polvoazul Same, plus I'm confused why there's a totally different positional parameter, `out`, so when naively switching `math.log(number, base)` to `np.log(array, base)`, you get confusing errors like `TypeError: 'float' object does not support item assignment` or `TypeError: return arrays must be of ArrayType`. Apparently all ufuncs have the `out` parameter, but if it were keyword-only, it'd be so much simpler. – wjandrea Feb 09 '23 at 18:12
1

Numpy's base n logarithm function is np.emath.logn.

import numpy as np
arr = np.array([74088, 3111696])      # = [42^3, 42^4]
base = 42
np.emath.logn(base, arr)              # array([3., 4.])

np.emath.logn(14, 14**3)              # 3.0

Note that unlike math.log, the base is the first argument. Also, unlike math.log, it can handle negative numbers (returns a complex number).

cottontail
  • 10,268
  • 18
  • 50
  • 51