将浮点数与三个小数位相比较 [英] Compare floats to three decimal places
问题描述
我想知道什么是比较浮点数和三个小数位的最快的方法。 > float lhs = 2.567xxxx
float rhs = 2.566xxxx
如果它像这样
float lhs = 2.566xxxx
float rhs = 2.566xxxx
它们应该是相同的
更新:
我正在尝试下列
double trunc )
{
return(d> 0)? floor(d):ceil(d);
}
bool comparisonigits(float a,float b)
{
if(trunc(1000.0 * a)== trunc(1000.0 * b ))
{
return true;
}
return false;
}
float g = 2.346;
float h = 2.34599;
bool t = comparigits(g,h); //不一样,应该返回false;
但是它返回true。
为了阻止错误的答案的冲击,因为它们允许四舍五入来改变结果,这里是一个没有舍入问题的答案,因为它使用 double
的算术运算:
trunc(1000。* lhs)== trunc 。* rhs);
这是因为 1000。
code> double ,因此另一个操作数从 float
转换为 double
,并且以 double
格式执行乘法。 1000与任何 float
值的乘积在 double
中可以精确表示,因此没有舍入误差(假设IEEE 754 32位和64位二进制浮点)。然后我们使用 trunc
来比较小数点之前的第三位数字。
I犹豫提供这个答案,因为我不知道这是OP真正想要的。通常当人们通过比较三个小数位的请求来到Stack Overflow时,他们没有完全考虑这个问题。完整的正确答案可能必须等到我们澄清。
此外,上述仅为正数。如果值可能为负,则应对其符号执行先前的测试,如果它们不同,则应返回 false
。 (否则,-.0009将被报告为等于+ 0.0009。)
I wanted to know what would be the fastest approach of comparing floats to three decimal places.Say I have something like this
float lhs = 2.567xxxx
float rhs = 2.566xxxx
The above should be different and if its something like this
float lhs = 2.566xxxx
float rhs = 2.566xxxx
They should be the same
Update:
I am trying the following
double trunc(double d)
{
return (d>0) ? floor(d) : ceil(d) ;
}
bool comparedigits(float a , float b)
{
if (trunc(1000.0 * a) == trunc(1000.0 * b))
{
return true;
}
return false;
}
float g = 2.346;
float h= 2.34599;
bool t = comparedigits(g,h) ; //Not the same and should return false;
However it is returning true.
To put a stop to the onslaught of answers that are wrong because they allow rounding to alter the results, here is an answer that does not have the rounding problem, because it uses double
for the arithmetic:
trunc(1000. * lhs) == trunc(1000. * rhs);
This works because 1000.
has type double
, so the other operand is converted from float
to double
, and the multiplication is performed in the double
format. The product of 1000 with any float
value is exactly representable in double
, so there is no rounding error (assuming IEEE 754 32-bit and 64-bit binary floating-point). Then we use trunc
to compare the numbers up to the (original) third digit after the decimal point.
I hesitated to provide this answer because I am not sure it is what the OP really wants. Often when people come to Stack Overflow with a request for comparing "to three decimal places", they have not entirely thought through the problem. A complete correct answer may have to wait until we have clarification.
Also, the above is for positive numbers only. If the values may be negative, then a prior test should be performed on their signs, and false
should be returned if they differ. (Otherwise, –.0009 would be reported as equal to +.0009.)
这篇关于将浮点数与三个小数位相比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!