意外的结果等于浮点数 [英] Unexpected results for floating point equals

查看:156
本文介绍了意外的结果等于浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题不是为什么 0.1 + 0.9 不等于 1.0 。它有关不同的行为等于。



有人可以解释为什么下面的例子工作不同。

  float q = 0.1f; 
浮点数w = 0.9f;
float summ = q + w;

q + w =​​= 1.0f; //假
summ == 1.0f; // True

为什么operator == 这个问题是由于中间计算是以更高的精度执行的,而这个规则是为了解决这个问题。什么时候回到 float precision在每种情况下都是不同的。 根据文档


<编译器使用协处理器的80位寄存器来保存浮点计算的中间结果。

float 类型的变量执行四舍五入到赋值和强制转换的正确精度,以及将参数传递给函数


float summ = q + w 是一个赋值,因此被舍入到最近的 floa t ,在这种情况下,它是1.



q + w =​​= 1.0f 既不是一个强制转换,赋值或函数调用,所以加法的结果仍然是一个扩展的精度浮点数,它接近但不等于1。

Question is not about why 0.1 + 0.9 is not equals 1.0. Its about different behaviour of a equals.

Can someone explain why examples below works differently.

float q = 0.1f;
float w = 0.9f;
float summ = q + w;

q + w == 1.0f; // False
summ == 1.0f; // True

Why operator == works differently?

解决方案

The problem is due to the fact that the intermediate calculations are being performed in a higher precision, and the rules for when to round back to float precision are different in each case.

According to the docs

By default, in code for x86 architectures the compiler uses the coprocessor's 80-bit registers to hold the intermediate results of floating-point calculations.

... the compiler performs rounding on variables of type float to the correct precision for assignments and casts and when parameters are passed to a function"

float summ = q + w is an assignment, and hence is rounded to the nearest float, which in this case is 1.

q + w == 1.0f is neither a cast, assignment or function call, so the result of the addition is still an extended precision float, which is close, but not equal, to 1.

这篇关于意外的结果等于浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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