在C浮点精确重新presentation [英] exact representation of floating points in c

查看:139
本文介绍了在C浮点精确重新presentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main()
{
    float a = 0.7;

    if (a < 0.7)
        printf("c");
    else
        printf("c++");
} 

在0.7以上问题,C将被打印,但对于0.8,C ++西港岛线进行打印。为什么呢?

In the above question for 0.7, "c" will be printed, but for 0.8, "c++" wil be printed. Why?

和如何以二进制形式psented任何浮动重新$ P $?

And how is any float represented in binary form?

目前有些地方,它被提及内部0.7将存储为0.699997,但0.8为0.8000011。为什么会这样?

At some places, it is mentioned that internally 0.7 will be stored as 0.699997, but 0.8 as 0.8000011. Why so?

推荐答案

基本上使用float你得到32位的EN code

basically with float you get 32 bits that encode

VALUE   = SIGN * MANTISSA * 2 ^ (128 - EXPONENT)
32-bits = 1-bit  23-bits               8-bits

和存储为

MSB                    LSB
[SIGN][EXPONENT][MANTISSA]

因为你只得到23位,这就是precision额你可以存储。如果你想重新present一小部分,不合理(或重复)在基地2个,比特序列将是四舍五入的第23位。

since you only get 23 bits, that's the amount of "precision" you can store. If you are trying to represent a fraction that is irrational (or repeating) in base 2, the sequence of bits will be "rounded off" at the 23rd bit.

0.7基地10是7月10日这在二进制文件0b111 / 0b1010你:

0.7 base 10 is 7 / 10 which in binary is 0b111 / 0b1010 you get:

0.1011001100110011001100110011001100110011001100110011... etc

由于该重复,在固定precision没有办法精确地重新present它。该
同样为0.8这在二进制文件:

Since this repeats, in fixed precision there is no way to exactly represent it. The same goes for 0.8 which in binary is:

0.1100110011001100110011001100110011001100110011001101... etc

要看看这些数字的固定precision值是你要切断它们在比特你的数量和做数学题。唯一的技巧就是你领先1是隐含的,没有存储,所以你得到技术上precision额外位。因为舍入,最后位将是1或0取决于截短位的值

To see what the fixed precision value of these numbers is you have to "cut them off" at the number of bits you and do the math. The only trick is you the leading 1 is implied and not stored so you technically get an extra bit of precision. Because of rounding, the last bit will be a 1 or a 0 depending on the value of the truncated bit.

所以0.7的值实际上是11744051/2 ^ 24(不四舍五入效果)= 0.699999988和0.8的价值实际上是13421773/2 ^ 24(四舍五入)= 0.800000012。

So the value of 0.7 is effectively 11,744,051 / 2^24 (no rounding effect) = 0.699999988 and the value of 0.8 is effectively 13,421,773 / 2^24 (rounded up) = 0.800000012.

这是所有有它:)

这篇关于在C浮点精确重新presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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