当前位置:   article > 正文

【numpy】【ndarray】指定每个元素保留小数点后多少位【around】【round】_array限制小数位数

array限制小数位数

dump_svmlight_file() 函数内部无法指定输出结果保留小数点后多少位,因此需提前调用函数限制小数点位数,相当于 python 原生的 round() 函数,引出 numpy.around() 函数。

numpy.around

numpy.around(adecimals=0out=None)

Evenly round to the given number of decimals.

参数

a : array_like

Input data.

decimals : int, optional

Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

out : ndarray, optional

Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See doc.ufuncs (Section “Output arguments”) for details.

返回值

rounded_array : ndarray

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

See also

ndarray.round

equivalent method

ceilfixfloorrinttrunc

Notes

For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [R9] and errors introduced when scaling by powers of ten.

Examples

  1. >>> np.around([0.37, 1.64])
  2. array([ 0., 2.])
  3. >>> np.around([0.37, 1.64], decimals=1)
  4. array([ 0.4, 1.6])
  5. >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
  6. array([ 0., 2., 2., 4., 4.])
  7. >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
  8. array([ 1, 2, 3, 11])
  9. >>> np.around([1,2,3,11], decimals=-1)
  10. array([ 0, 0, 0, 10])
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/726410
推荐阅读
相关标签
  

闽ICP备14008679号