numpy.round#
- numpy.round(a, decimals=0, out=None)[原始碼]#
均勻四捨五入到給定的小數位數。
- 參數:
- aarray_like
輸入資料。
- decimalsint, optional
要四捨五入到的小數位數 (預設值:0)。如果 decimals 為負數,則指定小數點左邊的位置數。
- outndarray, optional
放置結果的替代輸出陣列。它必須具有與預期輸出相同的形狀,但如果需要,將會轉換輸出值的類型。請參閱 輸出類型決定 以取得更多詳細資訊。
- 傳回值:
- rounded_arrayndarray
與 a 相同類型的陣列,包含四捨五入的值。除非指定了 out,否則會建立一個新陣列。傳回結果的參考。
複數的實部和虛部會分開四捨五入。浮點數四捨五入的結果是浮點數。
註解
對於精確地在四捨五入的小數值之間的值,NumPy 會四捨五入到最接近的偶數值。因此,1.5 和 2.5 四捨五入為 2.0,-0.5 和 0.5 四捨五入為 0.0,依此類推。
np.round
使用快速但有時不精確的演算法來四捨五入浮點資料類型。對於正數 decimals,它等效於np.true_divide(np.rint(a * 10**decimals), 10**decimals)
,由於 IEEE 浮點標準中十進制分數的不精確表示法 [1] 以及按十的冪縮放時引入的錯誤,因此會產生錯誤。例如,請注意以下額外的 “1”>>> np.round(56294995342131.5, 3) 56294995342131.51
如果您的目標是以固定的小數位數列印這些值,則最好使用 numpy 的浮點列印常式來限制列印的小數位數
>>> np.format_float_positional(56294995342131.5, precision=3) '56294995342131.5'
浮點列印常式使用精確但計算量更大的演算法來計算小數點後的位數。
或者,Python 的內建
round
函數對 64 位元浮點數值使用更精確但速度較慢的演算法>>> round(56294995342131.5, 3) 56294995342131.5 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997 (16.06, 16.05)
參考文獻
[1]“IEEE 754 狀態的講座筆記”,William Kahan,https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
範例
>>> import numpy as np >>> np.round([0.37, 1.64]) array([0., 2.]) >>> np.round([0.37, 1.64], decimals=1) array([0.4, 1.6]) >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value array([0., 2., 2., 4., 4.]) >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned array([ 1, 2, 3, 11]) >>> np.round([1,2,3,11], decimals=-1) array([ 0, 0, 0, 10])