c中浮点的精确表示 [英] exact representation of floating points in c

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

问题描述

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?

任何浮点数如何以二进制形式表示?

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位编码

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 位,这就是您可以存储的精度"数量.如果您试图表示以 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 base 10 是 7/10 二进制是 0b111/0b1010 你得到:

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

0.1011001100110011001100110011001100110011001100110011... etc

由于重复,因此无法以固定精度准确表示它.这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

要查看这些数字的固定精度值是多少,您必须根据您的位数将它们截断"并进行数学运算.唯一的窍门是你的前导 1 是隐含的,而不是存储的,所以你在技术上可以获得额外的精度.由于舍入,最后一位将是 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 的值实际上是 11,744,051/2^24(无舍入效果)= 0.699999988,0.8 的值实际上是 13,421,773/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.

这就是它的全部内容:)

That's all there is to it :)

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

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