Comparison of floating point values

This is a discussion on Comparison of floating point values within the C++ Programming forums, part of the General Programming Boards category; //code int testFunc(double value) double test = 0.0; if(val<=test) std::cout<<"Both are Equal"<<std::endl; /// The if loop may result to true ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    2

    Comparison of floating point values

    //code

    int testFunc(double value)

    double test = 0.0;

    if(val<=test)
    std::cout<<"Both are Equal"<<std::endl;


    ///

    The if loop may result to true if value ==0 but comparison of floating point values are not proper and violate the coding standard.
    How can I carry out such a comparison??????????

    Regards,
    Sanjib

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,623
    Because of floating point rounding errors, you may never end up with a float, or a double, which is exactly 0.0 ( unless you set it yourself ). That is why i use the following technique:

    Code:
    if ((val-ROUNDING_ERROR) <= test && (val+ROUNDING_ERROR) >= test)
    An alternative is the following:

    Code:
    if (fabs(val-test) <= ROUNDING_ERROR) // I'm not sure if that way works
    Which one you'll choose to use is up to you. For performance sake, i suggest the second one, but for simplicity the first.

    Code:
    val            :: The first number you want to compare
    test           :: The second number you want to compare
    ROUNDING_ERROR :: typical float tolerance is 0.0000001f , for double tolerance i'm not sure 
                       ( You can even use your own tolerance by passing in to the function.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 08-12-2010, 01:55 PM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  3. checking for floating point number
    By ssharish2005 in forum C Programming
    Replies: 6
    Last Post: 10-18-2005, 08:14 PM
  4. Floating point operand?
    By warny_maelstrom in forum C Programming
    Replies: 6
    Last Post: 03-04-2004, 11:26 AM
  5. Floating point numbers in a binary file
    By frenchfry164 in forum C++ Programming
    Replies: 6
    Last Post: 07-31-2003, 10:04 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21