19

python数据精度问题 - Mrwhite86

 3 years ago
source link: https://www.cnblogs.com/mrwhite2020/p/16637914.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python数据精度问题

一、python运算时精度问题:

1.运行时精度问题
在Python中(其他语言中也存在这个问题,这是计算机采用二进制导致的),有时候由于二进制和十进制之间对应问题会导致数值的精度问题,比如无法用有限个二进制位完整地表示0.1,因为0.1转化为二进制之后位一个无限循环小数

print(1.1*2.2)

 查看运行结果:

1767782-20220829235022436-1315765745.png

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)

查看运行结果:

1767782-20220830001820510-172847658.png

二、python四舍五入时精度问题:

1.使用round与浮点数格式化时候的精度问题

归根结底是计算机存储浮点数的问题

a1 = 0.235
a2 = round(a1,2)
a3 = '%.2f' % a1
print(a2)
print(a3)

查看运行结果:

1767782-20220830002238951-119460360.png

 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)

查看运行结果:

1767782-20220830003034512-1789869753.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK