使用 Python 中的 scimath 計算對數 2


若要使用 scimath 計算對數 2,請在 Python Numpy 中使用 np.emath.log2() 方法。該方法返回 x 值的以 2 為底的對數。如果 x 是標量,那麼 out 也是,否則會返回陣列。第一個引數 x 是需要計算以 2 為底的對數的值。

步驟

首先,匯入必需的庫 −

import numpy as np

使用 array() 方法建立一個 numpy 陣列 −

arr = np.array([np.inf, -np.inf, 16, np.exp(1), -np.exp(1), -32])

顯示陣列 −

print("Our Array...\n",arr)

檢查維度 −

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別 −

print("\nDatatype of our Array object...\n",arr.dtype)

獲取形狀 −

print("\nShape of our Array object...\n",arr.shape)

若要使用 scimath 計算對數 2,請在 Python Numpy 中使用 np.emath.log2() 方法。該方法返回 x 值的以 2 為底的對數。如果 x 是標量,那麼 out 也是,否則會返回陣列 −

print("\nResult (log2)...\n",np.emath.log2(arr))

示例

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([np.inf, -np.inf, 16, np.exp(1), -np.exp(1), -32])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To compute the logarithm base 2 with scimath, use the np.emath.log2() method in Python Numpy
# The method returns the log base 2 of the x value(s). If x was a scalar, so is out, otherwise an array is returned.
print("\nResult (log2)...\n",np.emath.log2(arr))

輸出

Our Array...
[ inf -inf 16. 2.71828183 -2.71828183
-32. ]

Dimensions of our Array...
1

Datatype of our Array object...
float64

Shape of our Array object...
(6,)

Result (log2)...
[ inf+0.j inf+4.53236014j 4. +0.j
1.44269504+0.j 1.44269504+4.53236014j 5. +4.53236014j]

更新於: 2022-03-01

161 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告