Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

c++ - Compare floats to three decimal places

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...