📌  相关文章
📜  如何使用 NumPy 计算给定数组中所有元素的自然对数、以 10 为底和以 2 为底的对数?

📅  最后修改于: 2022-05-13 01:55:39.721000             🧑  作者: Mango

如何使用 NumPy 计算给定数组中所有元素的自然对数、以 10 为底和以 2 为底的对数?

Python中的 numpy.log( )函数返回输入的自然对数,其中数字的自然对数是数学常数 e 的底的对数,其中 e 是一个无理数和超越数,大约等于 2.718281828459。

如果将标量作为输入提供给函数,则将函数应用于标量并返回标量。

示例:如果将 3 作为输入给出,则 log(3) 将作为输出返回。

Python3
import numpy
  
n = 3
print("natural logarithm of {} is".format(n), numpy.log(n))
  
n = 5
print("natural logarithm of {} is".format(n), numpy.log(n))


Python3
import numpy
  
  
arr = np.array([6, 2, 3, 4, 5])
print(numpy.log(arr))


Python
# importing numpy
import numpy
  
# natural logarithm
print("natural logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log(arr))
  
# Base 2 logarithm
print("Base 2 logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log2(arr))
  
# Base 10 logarithm
print("Base 10 logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log10(arr))


输出:

natural logarithm of 3 is 1.0986122886681098
natural logarithm of 5 is 1.6094379124341003

如果输入是一个 n-dim 数组,则按元素应用函数。 ex- np.log([1,2,3]) 等价于 [np.log(1),np.log(2),np.log(3)]

例子:

Python3

import numpy
  
  
arr = np.array([6, 2, 3, 4, 5])
print(numpy.log(arr))

输出:

[1.79175947 0.69314718 1.09861229 1.38629436 1.60943791]

类似于 numpy.log() 的函数:

  • numpy.log2() 计算以 2 为底的对数。此函数的参数与 numpy.log() 相同。它也被称为二进制对数。 y 的以 2 为底的对数是必须将数字 2 提高才能获得值 y 的幂。
  • numpy.log10() :计算以 10 为底的对数。参数与 numpy.log() 相同。 y 的以 10 为底的对数是数字 10 必须乘以得到 y 值的幂。

例子:

Python

# importing numpy
import numpy
  
# natural logarithm
print("natural logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log(arr))
  
# Base 2 logarithm
print("Base 2 logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log2(arr))
  
# Base 10 logarithm
print("Base 10 logarithm -")
arr = numpy.array([6, 2, 3, 4, 5])
print(numpy.log10(arr))

输出:

natural logarithm -
[1.79175947 0.69314718 1.09861229 1.38629436 1.60943791]
Base 2 logarithm -
[2.5849625  1.         1.5849625  2.         2.32192809]
Base 10 logarithm -
[0.77815125 0.30103    0.47712125 0.60205999 0.69897   ]