Thread: What is better, math or logic?

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

    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 09:26 AM. Reason: english

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Neither.

  3. #3
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    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,057
    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, 01:05 PM
  3. Basic Math Problem. Undefined Math Functions
    By gsoft in forum C Programming
    Replies: 1
    Last Post: 12-28-2004, 03:14 AM
  4. toughest math course
    By axon in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 10-28-2003, 10:06 PM