Python – 圆润的numpy?
发布时间:2020-12-20 11:58:30 所属栏目:Python 来源:网络整理
导读:我有 python pandas和numpy的奇怪问题. np.float64(1) * np.float64(85000) * np.float64(7.543709)641215.26500000001 round( np.float64(1) * np.float64(85000) * np.float64(7.543709),2 )641215.26000000001 np.round( np.float64(1) * np.float64(8500
我有
python pandas和numpy的奇怪问题.
>>> np.float64(1) * np.float64(85000) * np.float64(7.543709) 641215.26500000001 >>> round( np.float64(1) * np.float64(85000) * np.float64(7.543709),2 ) 641215.26000000001 >>> np.round( np.float64(1) * np.float64(85000) * np.float64(7.543709),2 ) 641215.26000000001 如何舍入才能得到正确的结果641215.27? 解决方法
Numpy的圆形方法有利于偶数,看看精简的numpy源代码:
def round_(a,decimals=0,out=None): return around(a,decimals=decimals,out=out) def around(a,out=None): """ Evenly round to the given number of decimals. 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 [1]_ and errors introduced when scaling by powers of ten. Examples -------- >>> np.around([0.37,1.64]) array([ 0.,2.]) >>> np.around([0.37,1.64],decimals=1) array([ 0.4,1.6]) >>> np.around([.5,1.5,2.5,3.5,4.5]) # rounds to nearest even value array([ 0.,2.,4.,4.]) >>> np.around([1,2,3,11],decimals=1) # ndarray of ints is returned array([ 1,11]) >>> np.around([1,decimals=-1) array([ 0,10]) """ 例: 如果你需要打印字符串,你可以格式化它,给你正确的答案: import numpy as np num = np.float64(1) * np.float64(85000) * np.float64(7.543709) print(num) print(float("{0:.2f}".format(num))) print(np.round(num,2)) print() num += 0.02 print(num) print(float("{0:.2f}".format(num))) print(np.round(num,2)) 给你 641215.265 641215.27 641215.26 641215.285 641215.29 641215.28 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |