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

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

> 语法: numpy.log(arr, out)

>

> 参数:

> arr: 输入值。可以是标量,也可以是 numpy n维数组。

> out: 存储结果的位置。如果提供该参数,其形状必须与输入广播后的形状相匹配。如果未提供或为 None,则返回一个新分配的数组。形状必须与输入数组相同。

如果向函数提供的是一个标量作为输入,那么该函数将作用于该标量,并返回一个标量。

示例: 如果输入 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))

输出:

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

如果输入是一个 n 维数组,则该函数将逐元素(element-wise)地应用。例如,INLINECODE6301dc61 等同于 INLINECODEe2b9fb11。

示例:

            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   ]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/30888.html
点赞
0.00 平均评分 (0% 分数) - 0