0

I'm new to Visual C++, i have two double variables, let say AA = 10.650406 while b = 10.65040606439, how can i make them equal?

here is an example

AA = 10.650406;

if (a == tempfunc(zz)) execute TRUEFUNCTION else exceute FALSEFUNCTION

the variable AA is a double while the function tempfunc return double, if the value AA is 10.650406, while the return value of tempfunc is 10.65040606439. the question is how can make these value equal so i can execute the function TRUEFUNCTION

ibulseco
  • 47
  • 4
  • 6
  • This question is likely a duplicate of this http://stackoverflow.com/questions/13940316/floating-point-comparison-revisited and/or this http://stackoverflow.com/questions/17380970/how-can-i-check-whether-two-numbers-are-within-x-significant-figures-of-the-pr – amdn Apr 03 '14 at 06:58
  • 3
    Why down-votes, whats wrong with question. It is really discoursing for new people. – Pranit Kothari Apr 03 '14 at 07:00

2 Answers2

2

The typical solution is to compare the difference, using an "epsilon value". Something like

const double eps = 0.000001;  // Adjust this to match the "perecision" you need.

if (abs(a-b) < eps)
{
    // Values are almost equal
}
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • This is exactly what I would recommend doing. If C++11 libraries are available then std::numeric_limits::epsilon can also help with deciding what precision to use. Although that may not be needed by user3492409. – Rastaban Apr 03 '14 at 17:43
  • I suspect, in this case, that `std::numeric_limit::epsilon` (or the C99 standard constant of DBL_EPSILON) isn't what is needed - as I understand the question it's about "is the value nearly the same". The epsilon value will represent the very smallest value difference that can be distinguished in the type. If you want to, for example, see if the value is "the same down to a cent of a dollar", the epsilon should be 0.01, not the epsilon value for a `float` or `double`. – Mats Petersson Apr 03 '14 at 21:05
0

I guess your question is: how to have a check that would be true for these two numbers, but not for all..:

10.123 == 10.1234 (TRUE)
10.123 == 11.123 (FALSE)

if you have a fixed number of digits after the decimal separator (6 in your example), you could do this:

int a2 = a * 10e6;
int b2 = b * 10e6; // (conversion to integers; so the digits smaller than the 6th digit will be removed)

Now you can check:

if (a2 == b2)
    {
    //do your thing
    }

in short:

if ( ((int) a*10e6) == ((int) b*10e6))
    {
    //do your thing
    }
Chris Maes
  • 35,025
  • 12
  • 111
  • 136