为什么比较 double 和 float 会导致意外结果?
可能的重复:
浮点与浮点文字比较的奇怪输出
float f = 1.1;
double d = 1.1;
if(f == d) // returns false!
为什么会这样?
推荐答案
float
或 double
数字考虑的重要因素是:
精度 &四舍五入
The important factors under consideration with float
or double
numbers are:
Precision & Rounding
精度:
浮点数的精度是它可以表示多少位而不丢失它包含的任何信息.
考虑分数 1/3
.这个数字的十进制表示是0.33333333333333…
,其中3 向无穷大.一个无限长的数字需要无限的内存来精确地描述,但是 float
或 double
数据类型通常只有 4
或 8
字节.因此浮点数 &双数只能存储一定数量的数字,其余的肯定会丢失.因此,没有明确准确的方法来表示浮点数或双精度数需要比变量所能容纳的精度更高的数字.
Consider the fraction 1/3
. The decimal representation of this number is 0.33333333333333…
with 3′s going out to infinity. An infinite length number would require infinite memory to be depicted with exact precision, but float
or double
data types typically only have 4
or 8
bytes. Thus Floating point & double numbers can only store a certain number of digits, and the rest are bound to get lost. Thus, there is no definite accurate way of representing float or double numbers with numbers that require more precision than the variables can hold.
四舍五入:binary
和 decimal (base 10)
数字之间存在不明显的差异.
考虑分数 1/10
.在decimal
中,这可以很容易地表示为0.1
,而0.1
可以被认为是一个易于表示的数字.但是,在二进制中,0.1
用无限序列表示:0.00011001100110011…
Rounding:
There is a non-obvious differences between binary
and decimal (base 10)
numbers.
Consider the fraction 1/10
. In decimal
, this can be easily represented as 0.1
, and 0.1
can be thought of as an easily representable number. However, in binary, 0.1
is represented by the infinite sequence: 0.00011001100110011…
示例:
#include <iomanip>
int main()
{
using namespace std;
cout << setprecision(17);
double dValue = 0.1;
cout << dValue << endl;
}
这个输出是:
0.10000000000000001
没有
0.1.
这是因为 double 由于内存有限而不得不截断近似值,这导致数字不完全是 0.1
.这种情况称为舍入误差.
This is because the double had to truncate the approximation due to it’s limited memory, which results in a number that is not exactly 0.1
. Such an scenario is called a Rounding error.
每当比较两个接近的浮点数和双精度数时,就会出现这种舍入错误,最终比较会产生不正确的结果,这就是您永远不应该使用 ==
比较浮点数或双精度数的原因.
Whenever comparing two close float and double numbers such rounding errors kick in and eventually the comparison yields incorrect results and this is the reason you should never compare floating point numbers or double using ==
.
你能做的最好的事情就是计算它们的差异并检查它是否小于一个 epsilon.
The best you can do is to take their difference and check if it is less than an epsilon.
abs(x - y) < epsilon
相关文章