浮点的二进制表示 [英] binary representation of a float

查看:145
本文介绍了浮点的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这两个调用toBinary函数计算相同的输出(至少在VS2010下)?

why this two call to toBinary function compute the same output (at least under VS2010) ?

#include <iostream>
#include <bitset>
#include <limits>
using namespace std;

template<class T> bitset<sizeof(T)*CHAR_BIT> toBinary(const T num) 
{
    bitset<sizeof(T)*CHAR_BIT> mybits;
    const char * const p = reinterpret_cast<const char*>(&num);
    for (int i = sizeof(T)*CHAR_BIT-1 ; i >= 0 ; --i)
        mybits.set(i, (*(p)&(1<<i) ));
    return mybits;
}

int main() 
{
    cout << toBinary(8.9).to_string() << "\n"; 
    cout << toBinary( 8.9 + std::numeric_limits<double>::epsilon() ).to_string()  << "\n"; 
    cin.get();
}


推荐答案

;在这里,相反,你将它的总和为8.9,这是大于8(2 ^ 3)倍大于1.这意味着epsilon将改变一个二进制数字,最右边的数字的右边三位数存储在双重。

That epsilon is relative to 1; here, instead, you are summing it to 8.9, which is more than 8 (2^3) times bigger than 1. This means that that epsilon would change a binary digit that is three digits to the right of the rightest digit stored in that double.

如果您想注意到某些变化,您必须添加大约8.9 * epsilon。

If you want to notice something change, you have to add at about 8.9*epsilon.

这篇关于浮点的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆