Thread: Have I written the macros correctly ?

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    87

    Have I written the macros correctly ?

    Hi, I'm trying to write a macro for the relative difference function which is used to check the close enough floating point values. This is the relative difference function. I want to write a macro instead :

    Code:
    #define Abs(x)     ((x < 0 ? -(x) : (x))
    #define Max(a,b) ((a) > (b) ? (a) : (b))
    
    double reldif( double a, double b)
    {
      double c = Abs(a);
      double d = Abs(b);
    
      d = Max(c,d);
      return d == 0.0 ? 0.0 : Abs(a-b)/d;
    }
    
    
    Then for checking equality of two floating points :
    #define EPSILON 0.000001
    .....
    if ( reldif(a, b) <= TOLERANCE)

    And here's my macro eq(a,b):

    Code:
    #define max(x, y) ((x) > (y) ?  (x) : (y)) 
    #define eq(a, b)  max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs(a - b) / (max(fabs(a), fabs(b)))
    So we can simply write eq(a,b) <= EPSILON

    can some one please tell me if this is correct or not ?
    Last edited by broli86; 06-29-2008 at 04:14 AM.

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    It seems so. Test them to be sure.

  3. #3
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    Well, have you tested it ?

    As far as I see, it should be fine. But you should add an extra pair or two of paranthesis
    Code:
    #define eq(a, b)  (max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs((a) - (b)) / (max(fabs(a), fabs(b))))
    Personally I would stay with a normal function.
    I hate real numbers.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    87
    I have just tested them and it worked for all examples I took . I'm sometimes wary of using macros though because you never know whether it has gone wrong some place.
    Last edited by broli86; 06-29-2008 at 07:15 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pre-processor macros causing segfaults
    By nempo in forum C++ Programming
    Replies: 6
    Last Post: 02-10-2009, 02:35 AM
  2. using getenv correctly
    By cus in forum Linux Programming
    Replies: 3
    Last Post: 01-04-2009, 12:32 PM
  3. have i written this program correctly ?
    By broli86 in forum C Programming
    Replies: 6
    Last Post: 07-20-2008, 03:20 PM
  4. Visual C++ and UNICODE - _t macros
    By nvoigt in forum Windows Programming
    Replies: 2
    Last Post: 04-22-2005, 07:42 AM
  5. template fn replacements for msg macros
    By Ken Fitlike in forum Windows Programming
    Replies: 17
    Last Post: 10-30-2002, 07:55 AM