为什么 0.1+0.2= 0.300000004 float32 python实现

IEEE浮点数尾数向偶舍入-四舍六入五成双

# -*- coding: utf-8 -*-
"""
Created on Thu Jun  9 17:20:29 2022

@author: luogantt
"""

import numpy as np

#将十进制小数转化为二进制
def dec2bin(x):
  x -= int(x)
  bins = []
  while x:
    x *= 2
    bins.append(1 if x>=1. else 0)
    x -= int(x)
  return bins
print(dec2bin(.8125))


def expo(cc):
   
    n=0
    while (not cc[n]):
        n=n+1
        print(n)
    return n+1



"""
  >0.5           --1
  <0.5           --0
  ==0.5 if up==0 --0
  ==0.5 if up==1 --1 
"""

#决定舍入项是否要进一位
def roundings(cc,exp):
    drop= np.array(cc[exp+23:exp+23+4])
    weight=np.array([1/2,1/4,1/8,1/16])
    
    ifdrop=np.sum(weight*drop)
    
    if ifdrop>0.5:
        return 1
    elif  ifdrop<0.5:
        return 0
    else:
        if cc[exp+23]==0:
            return 0
        else:
            return 1 
        
        

# 将小数位转换成 float32 
def float32(exp,cc):
    
    fric=cc[exp:exp+23]
    
    strfric=''.join([str(k) for k in fric])
    intfric= int(strfric,2)
    
    round1= roundings(cc,exp)
    
    if round1:
        intfric=intfric+1
    
    intfric1=bin(intfric)
    intfric2=intfric1[2:]
    
    intfric3=[int(k) for k in intfric2]
    
    sum=0
    for k in range(len(intfric3)):
        sum=sum+intfric3[k]*2**(-1*(k+exp+1))
    sum=sum+(2)**(-(exp))
        
    print(sum)
    
    return sum



cc1=dec2bin(0.1)
exp1=expo(cc1)
sum1= float32(exp1,cc1)
print( '小数位',sum1)

cc2=dec2bin(0.2)
exp2=expo(cc2)
sum2= float32(exp2,cc2)
print(sum2)
#
print('0.1+0.2=',sum1+sum2)
[1, 1, 0, 1]
1
2
3
0.10000000149011612
小数位 0.10000000149011612
1
2
0.20000000298023224
0.20000000298023224
0.1+0.2= 0.30000000447034836

IEEE浮点数尾数向偶舍入-四舍六入五成双

posted @ 2022-08-19 22:43  luoganttcc  阅读(8)  评论(0编辑  收藏  举报