在 Numpy 中計算單位階躍函式
要計算單位階躍函式,在 Python Numpy 中使用 numpy.heaviside() 方法。第 1 個引數是輸入陣列。第 2 個引數是陣列元素為 0 時的函式值。返回輸出陣列,element-wise Heaviside step function of x1。如果 x1 和 x2 都是標量,則這是一個標量。
單位階躍函式定義為 −
0 if x1 < 0 heaviside(x1, x2) = x2 if x1 == 0 1 if x1 > 0
其中 x2 通常取為 0.5,但也經常使用 0 和 1。
步驟
首先,匯入必需的庫 −
import numpy as np
使用 array() 方法用浮點型別建立一個數組 −
arr = np.array([50.8, -3.5, 120.3, 0, 320.1, 450.4, 0])
顯示陣列 −
print("Array...
", arr)
獲取陣列的型別 −
print("
Our Array type...
", arr.dtype)獲取陣列的維度 −
print("
Our Array Dimension...
",arr.ndim)
獲取陣列的形狀 −
print("
Our Array Shape...
",arr.shape)要計算單位階躍函式,在 Python Numpy 中使用 numpy.heaviside() 方法。第 1 個引數是輸入陣列。第 2 個引數是陣列元素為 0 時的函式值 −
print("
Result...
",np.heaviside(arr, 1))
示例
import numpy as np
# Create an array with float type using the array() method
arr = np.array([50.8, -3.5, 120.3, 0, 320.1, 450.4, 0])
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Our Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Our Array Dimension...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# To compute the Heaviside step function, use the numpy.heaviside() method in Python Numpy
# The 1st parameter is the input array
# The 2nd parameter is the The value of the function when array element is 0
print("
Result...
",np.heaviside(arr, 1))輸出
Array... [ 50.8 -3.5 120.3 0. 320.1 450.4 0. ] Our Array type... float64 Our Array Dimension... 1 Our Array Shape... (7,) Result... [1. 0. 1. 1. 1. 1. 1.]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP