详解Python中的数据精度问题
作者:Mrwhite86 时间:2022-08-17 13:36:22
一、python运算时精度问题
1.运行时精度问题
在Python中(其他语言中也存在这个问题,这是计算机采用二进制导致的),有时候由于二进制和十进制之间对应问题会导致数值的精度问题,比如无法用有限个二进制位完整地表示0.1,因为0.1转化为二进制之后位一个无限循环小数
print(1.1*2.2)
查看运行结果:
2.解决方案:添加方法
需要将整数部分与小数部分单独做处理可以解决
def multiple(m1, m2):
r=''
## 若存在浮点型,则先转化为整数
if type( m1 )==float or type( m2 )==float:
print( "存在浮点数" )
len_m1=len( str( m1 ).split( "." )[1] )
len_m2=len( str( m2 ).split( "." )[1] )
print( "m1的小数位:", len_m1 )
print( "m2的小数位:", len_m2 )
m1=int( 10**len_m1*m1 )
m2=int( 10**len_m2*m2 )
print( "m1化为整数:", m1 )
print( "m2化为整数:", m2 )
r=str( m1*m2 )
print( "r:", r )
l=len_m1+len_m2
print( "l的总长度:", l )
if l<len( r ):
r_front=r[:-l]
r_last=r[-l:]
print( r_front, "-", r_last )
r=r_front+"."+r_last
else:
r="0."+(l-len( r ))*"0"+r
else:
print( "不存在浮点数" )
r=m1*m2
return r
res = multiple(1.1,2.2)
print(res)
查看运行结果:
二、python四舍五入时精度问题
1.使用round与浮点数格式化时候的精度问题
归根结底是计算机存储浮点数的问题
a1 = 0.235
a2 = round(a1,2)
a3 = '%.2f' % a1
print(a2)
print(a3)
查看运行结果:
2.解决方案,使用Decimal函数
需要将float转换为Decimal,该类可以通过接受字符串(务必是字符串)形式的浮点数实现相对精确的小数计算(减缓了精度误差,但没有消灭)
from decimal import Decimal
a1 = 0.235
a2 = Decimal(str(a1)).quantize(Decimal("0.00"))
a3 = '{:.2f}'.format(Decimal(str(a1)))
print(a2)
print(a3)
查看运行结果:
来源:https://www.cnblogs.com/mrwhite2020/p/16637914.html
标签:Python,数据,精度
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python设计模式之命令模式原理与用法实例分析
2022-07-28 20:49:15
![](https://img.aspxhome.com/file/2023/4/75314_0s.png)
pandas数值排序的实现实例
2022-05-13 01:36:48
![](https://img.aspxhome.com/file/2023/7/75247_0s.png)
用ajax实现的自动投票的代码
2023-08-24 16:35:07
形式追随内容?
2010-03-07 15:55:00
![](https://img.aspxhome.com/file/UploadPic/20103/7/ryan100224_01-77s.jpg)
js给静态网页代码加密方法
2007-08-04 19:48:00
儿童python练习实例
2023-12-13 04:26:32
Python字符串函数strip()原理及用法详解
2021-12-01 12:08:12
javascript彩虹圈效果
2011-08-05 19:10:45
Python脚本传参数argparse模块的使用
2023-02-28 23:07:21
![](https://img.aspxhome.com/file/2023/4/97724_0s.png)
pyqt5对用qt designer设计的窗体实现弹出子窗口的示例
2023-01-28 12:58:07
css基础教程属性篇之盒子模型
2008-07-29 12:05:00
![](https://img.aspxhome.com/file/UploadPic/20087/29/2008729121433524s.jpg)
基于win2003虚拟机中apache服务器的访问
2023-11-14 11:17:08
![](https://img.aspxhome.com/file/2023/9/55609_0s.jpg)
python list转置和前后反转的例子
2022-04-26 10:39:55
![](https://img.aspxhome.com/file/2023/9/81719_0s.jpg)
网页设计者应当注意九大要点
2007-08-10 13:30:00
Bootstrap table的使用方法
2023-09-10 13:34:47
![](https://img.aspxhome.com/file/2023/4/56254_0s.jpg)
Python实现连接两个无规则列表后删除重复元素并升序排序的方法
2021-05-23 10:35:54
![](https://img.aspxhome.com/file/2023/2/82602_0s.png)
动态提示的select下拉框
2007-12-02 14:54:00
pythotn条件分支与循环详解(3)
2023-11-14 01:35:06
![](https://img.aspxhome.com/file/2023/9/80599_0s.png)
Python使用Keras OCR实现从图像中删除文本
2022-07-22 20:50:24
![](https://img.aspxhome.com/file/2023/9/80569_0s.jpg)
centos7利用yum安装lnmp的教程(linux+nginx+php7.1+mysql5.7)
2023-11-14 11:40:18