为什么 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浮点数尾数向偶舍入-四舍六入五成双

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值