比较相同的浮点值奇怪的输出? [英] Strange output when comparing same float values?

查看:137
本文介绍了比较相同的浮点值奇怪的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较C中的相同浮动值



比较浮动的奇怪输出with float literal

浮点数增加了两倍?






我读了浮点上面的链接, 。

  #include< stdio.h> 
int main()
{
float x = 0.5;

if(x == 0.5)
printf(IF);

else if(x == 0.5f)
printf(ELSE IF);

else
printf(ELSE);





$现在,根据促销规则,不应该 ELSE IF 必须打印?



但是,这里是打印 IF





编辑:是因为二进制中的0.5 = 0.1,而且之后一切都是0,精度的损失因此没有效果,所以比较 IF 返回true。



如果是0.1,0.2,0.3,0.4,0.6,0.7 ....那么 Else如果块返回true。






请原谅我提出同样的问题,因为我从上面的链接浮动比较绝不能做。



但是,这种意外行为的原因是什么?

解决方案


浮点数是不准确的。

这种说法是错误的。一些浮点数是准确的,如1.0,12345.0,12345.5,-2.25。所有这些数字都可以表示为由2的幂作为整数。所有数字不能也不准确。

在您的具体情况下, float x = 0.5 结果为 x ,其值 1.00000000 * 2 ^ -1 。当你把它与 double 0.5 进行比较时,两个操作数都被转换为 double ,所以比较变成 1.000000000000000 * 2 ^ -1 == 1.000000000000000 * 2 ^ -1 ,即可成功

float x = 0.1 ,看起来不一样。该值存储为 1.01010101 * 2 ^ -3 (或类似)。请注意,这已经不准确了。当你把它和 double 0.1 进行比较时,float在最后加零,比较变成 1.010101010000000 * 2 ^ -3 == 1.010101010101010 * 2 ^ -3 ,失败。


Comparing Same Float Values In C

strange output in comparison of float with float literal

Float addition promoted to double?


I read the above links on floating points, but even getting strange output.

#include<stdio.h>
int main()
{
    float x = 0.5;

    if (x == 0.5)
        printf("IF");

    else if (x == 0.5f)
        printf("ELSE IF");

    else
        printf("ELSE");
}

Now, according to the promotion rules, Shouldn't "ELSE IF" must be printed ?

But, here it is printing "IF"


EDIT : Is it because 0.5 = 0.1 in binary and everything is 0 after that and loss of precision hence no effects, so comparison IF returns true.

Had it been 0.1, 0.2, 0.3, 0.4, 0.6, 0.7.... , then Else If block returns true.


Pardon me asking same question, because I have read from the above links that floats comparison must never be done.

But, What is the reason of this unexpected behaviour ?

解决方案

Floating point numbers are never accurate.

This statement is wrong. Some floating point numbers are accurate, such as 1.0, 12345.0, 12345.5, -2.25. All these numbers can be represented as integers didived by a power of 2. All numbers that cannot also are not accurate.

In your specific case, float x = 0.5 results in x having the value 1.00000000 * 2^-1. When you compare this against double 0.5, both operands are converted to double, so the comparison becomes 1.000000000000000 * 2^-1 == 1.000000000000000 * 2^-1, which succeeds.

For float x = 0.1, it looks different. The value is stored as 1.01010101 * 2^-3 (or similar). Note that this is already not precise. When you compare this against double 0.1, the float is extended with zeros at the end, the comparison becomes 1.010101010000000 * 2^-3 == 1.010101010101010 * 2^-3, which fails.

这篇关于比较相同的浮点值奇怪的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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