Python 中向零取整


要將浮點數向零取整,可以使用 Python Numpy 中的 numpy.fix() 方法。它將浮點數陣列逐元素四捨五入到最接近的整數(向零方向)。舍入後的值以浮點數形式返回。第一個引數 x 是要舍入的浮點數陣列。第二個引數 out 是儲存結果的位置。如果提供,則其形狀必須是輸入廣播到的形狀。如果沒有提供或為 None,則返回一個新分配的陣列。

該方法返回一個與輸入具有相同維度的浮點數陣列。如果未提供第二個引數,則返回一個包含舍入值的浮點數陣列。如果提供了第二個引數,則結果將儲存在那裡。然後,返回值 out 是對該陣列的引用。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立一個浮點型陣列 -

arr = np.array([120.6, -120.6, 200.7, -320.1, 320.1, 500.6])

顯示我們的陣列 -

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

獲取資料型別 -

print("\nArray datatype...\n",arr.dtype)

獲取陣列的維度 -

print("\nArray Dimensions...\n",arr.ndim)

獲取陣列的元素數量 -

print("\nNumber of elements in the Array...\n",arr.size)

要將浮點數向零取整,可以使用 Python Numpy 中的 numpy.fix() 方法。它將浮點數陣列逐元素四捨五入到最接近的整數(向零方向)。舍入後的值以浮點數形式返回 -

print("\nResult (rounded)...\n",np.fix(arr))

示例

import numpy as np

# Create an array with float type using the array() method
arr = np.array([120.6, -120.6, 200.7, -320.1, 320.1, 500.6])

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

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimension...\n",arr.ndim)

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

# To round to nearest integer towards zero, use the numpy.fix() method in Python Numpy
# It rounds an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.
print("\nResult (rounded)...\n",np.fix(arr))

輸出

Array...
[ 120.6 -120.6 200.7 -320.1 320.1 500.6]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result (rounded)...
[ 120. -120. 200. -320. 320. 500.]

更新於: 2022-02-28

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告