What is better, math or logic?

This is a discussion on What is better, math or logic? within the C++ Programming forums, part of the General Programming Boards category; Take the following code snippets that find the absolute value of the variable x. This one uses logic: Code: if ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    197

    What is better, math or logic?

    Take the following code snippets that find the absolute value of the variable x.

    This one uses logic:
    Code:
    if ( x < 0 )
    x *= -1.0f;
    And this one which uses math:
    Code:
    x = fabsf( x );
    Given that the probability of x being negative is equal to the probability of x being positive, which of the two methods is best?
    Last edited by thetinman; 02-24-2006 at 08:26 AM. Reason: english

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,506
    Neither.

  3. #3
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    Don't know much about how floating-point works indepth but I think that
    Code:
    if ( x < 0 )
        x = -x;
    would be faster for the first method.

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    The compiler would probably optimise both to be the same thing (assuming you meant fabs(), not fabsf()).
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Math
    By knightjp in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 04-01-2009, 05:36 PM
  2. Digital Logic
    By strokebow in forum Tech Board
    Replies: 3
    Last Post: 12-09-2006, 12:05 PM
  3. Basic Math Problem. Undefined Math Functions
    By gsoft in forum C Programming
    Replies: 1
    Last Post: 12-28-2004, 02:14 AM
  4. toughest math course
    By axon in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 10-28-2003, 09:06 PM

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