总结一下小数精度的处理问题
一、round()函数内置方法
round(number,[ndigits]):round 对传入的数据进行四舍五入,但并不是传统意义上的四舍五入。number:需要被处理的参数;ndigits:保留的位数。
ndigits:不取值,number的小数部分没有0.5的时候,则按照四舍五入进行取值;
不取值,number的小数部分存在0.5的时候,round()取靠近的偶数;
取值,number的小数部分没有.5的时候,则按照四舍五入进行取值;
取值,number的小数部分存在.5的时候,小数位前是奇数则舍弃,小数位前是偶数则向上取(意味着,一旦出现小数位后为.5的,则小数位前取值,无法取到偶数);
#ndigits 不取值的时候
print("1:", round(2.5)) #存在0.5,取值靠近偶数: 2
print("2:", round(2.55)) #不存在0.5,取值按照四舍五入:3
print("3:", round(3.5)) #存在0.5,取值靠近偶数:4
print("4:", round(4.5)) #存在0.5,取值靠近偶数:4
print("5:", round(4.54)) #不存在0.5,取值按照正常的四舍五入
print("6:", round(5.5)) #存在0.5,取值靠近偶数:6
#ndigits 取值的时候
print("7:", round(2.635, 2)) #存在.5,小数位前奇数: 2.63
print("8:", round(2.645, 2)) #存在.5,小数位前偶数:2.65
print("9:", round(2.655, 2)) #存在.5,小数位前奇数:2.65
print("10:", round(2.665, 2)) #存在.5,小数位前偶数:2.67
print("11:", round(2.675, 2)) #存在.5,小数位前奇数:2.67
print("12:", round(2.634, 2)) #不存在.5,按照四舍五入: 2.63
print("13:", round(2.636, 2)) #不存在.5,按照四舍五入: 2.64
二、格式化处理
输出格式%.mf:处理机制个round()函数一致,m指取得位数,f是指float数据类型
#m不取值的时候
print("1: %.f" % 2.5) #存在0.5,取值靠近偶数: 2
print("2: %.f" % 3.5) #存在0.5,取值靠近偶数: 4
print("3: %.f" % 3.4) #不存在0.5,按照四色五入: 2
print("4: %.f" % 3.6) #不存在0.5,按照四舍五入: 2
#m=2 取值的时候
print("4: %.2f" % 2.635) #存在.5,小数位前奇数: 2.63
print("5: %.2f" % 2.645) #存在.5,小数位前偶数:2.65
print("6: %.2f" % 2.655) #存在.5,小数位前奇数:2.65
print("7: %.2f" % 2.665) #存在.5,小数位前偶数:2.67
print("8: %.2f" % 2.675) #存在.5,小数位前奇数:2.67
print("9: %.2f" % 2.634) #不存在.5,按照四舍五入: 2.63
三、超过17位精度分析
python中默认的为17位小数精度,但如果我们需要使用更高精度的时候(意味着超过17位小数),如果处理?
使用前面两种方法进行处理,查看一下处理结果:
print("1: %.30f" % (1/3)) #输出:1: 0.333333333333333314829616256247
print("2: %s" % round((1/3), 30)) #输出:2: 0.3333333333333333
显然前面两种方法是不适用的,round()内置函数其结果只能取到小数点后16位;而格式化处理虽然可以取到30位,但其精度是不准确的。
下面介绍一种方法:高精度使用 decimal模块,配合getcontext
print(getcontext())
getcontext().prec= 50 #设置全局精度
b = Decimal(1)/Decimal(3)print(b)
c= Decimal(1)/Decimal(17)print(float(c))
四、关于小数和取整
1.math模块下的ceil(x)函数:取大于或者等于x的最小整数
2.math模块下的floor(x)函数:取小于或者等于x的最大整数
from math importceil, floor#ceil():取大于或等于x的最小整数
print("1: %s" % ceil(2.5)) #1: 3
print("2: %s" % ceil(2.3)) #2: 3
print("3: %s" % ceil(2.6)) #3: 3
#floor():取小于或等于x的最大整数
print("4: %s" % floor(2.5)) #4: 2
print("5: %s" % floor(2.3)) #5: 2
print("6: %s" % floor(2.6)) #6: 2
五、截取小数点后bit位
编写函数cut(self,bit)进行处理
defcut(self, bit):
str_sli= str(self).split('.', 1)
sli= len(str_sli[0]) + bit + 1result=str(self)[:sli]returnresult
a= cut(3.1356, 2)print(a) #输出结果为: 3.13