在 NumPy 中返回下一個浮點值並將結果儲存到新的位置
要在 Python NumPy 中按元素返回一個值之後朝另一個值方向的下一個浮點值,請使用 **numpy.nextafter()** 方法。第一個引數是要查詢其下一個可表示值的數值。第二個引數是查詢下一個可表示值的方向。我們將儲存結果的新位置是一個新的陣列。
此函式返回 x1 朝 x2 方向的下一個可表示值。如果 x1 和 x2 都是標量,則它也是標量。
out 是儲存結果的位置。如果提供,則其形狀必須與輸入廣播到的形狀相同。如果不提供或為 None,則返回一個新分配的陣列。元組(僅作為關鍵字引數可能)的長度必須等於輸出的數量。
條件在輸入上廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化。
步驟
首先,匯入所需的庫:
import numpy as np
使用 array() 方法建立兩個零維 NumPy 陣列:
arr1 = np.array(0.1) arr2 = np.array(-np.inf)
顯示陣列:
print("Array 1...
", arr1)
print("
Array 2...
", arr2)獲取陣列的型別:
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)獲取陣列的維度:
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)建立另一個具有相同形狀的陣列來儲存結果:
arrRes = np.array(8.7)
要返回一個值之後朝另一個值方向的下一個浮點值,請使用 numpy.nextafter() 方法。我們將儲存結果的新位置是 arrRes:
print("
The next floating-point value...
",np.nextafter(arr1, arr2, arrRes))檢查儲存結果的新陣列的值:
print("
Result...
",arrRes)
示例
import numpy as np
# Creating two zero dimensional numpy array using the array() method
arr1 = np.array(0.1)
arr2 = np.array(-np.inf)
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Create another array with the same shape to store the result
arrRes = np.array(8.7)
# To return the next floating-point value after a value towards another value, element-wise, use the numpy.nextafter() method in Python Numpy
# The 1st parameter is the value to find the next representable value of.
# The 2nd parameter is the direction where to look for the next representable value.
# The new location where we will store the result is arrRes
print("
The next floating-point value...
",np.nextafter(arr1, arr2, arrRes))
# Check the value of the new array where our result is stored
print("
Result...
",arrRes)輸出
Array 1... 0.1 Array 2... -inf Our Array 1 type... float64 Our Array 2 type... float64 Our Array 1 Dimensions... 0 Our Array 2 Dimensions... 0 The next floating-point value... 0.09999999999999999 Result... 0.09999999999999999
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP