Thread: log(x) - log(y) vs log(x/y)

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    9

    log(x) - log(y) vs log(x/y)

    Does anyone have an idea on which of these runs faster, or is my compiler "smart" enough to pick the right one for me?

    Code:
    double x=10.0;
    double y=5.0;
    
    double z = log(x/y);
    Alternatively, the last line could be written as:
    Code:
    double z = log(x) - log(y);
    What about this case:
    Code:
    double w=2.0;
    double x=10.0;
    double y=5.0;
    
    double z = log(sqrt(w*x)/y);
    Alternatively, the last line could be written as:
    Code:
    double z = 0.5*log(w*x) - log(y);
    Thanks very much for your help.

  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
    Well 1 log call is going to be cheaper than two

    sqrt() is probably cheaper than log, so sqrt+log is likely better than log+log

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    One log call is not necessarily going to be cheaper than two. One (not uncommon) way of implementing multiplication and division at the hardware level is via log and exponential tables. You might recall the the pentium FDIV bug (related to the hardware floating point division done by early pentium CPUs) was actually the result of an error in tables used internally by the FDIV instruction.

    Regardless of any relative speed advantage in this case, I would actually use subtraction of logs in practice for computing log(x/y). Computing x/y can overflow for large x and small y (and taking the log of the result of that does not give back the intended value), but computing the log of each and taking the difference will not involve overflow.

    Similarly, if I care about not overflowing for computing log(sqrt(w*x)/y), I would do it as log(w) + log(x) - log(y) - log(2.0);

    If you are really concerned about performance (by which you presumably mean speed of calculation), and are willing to accept possibility of overflow or underflow to achieve that, then the only way to be certain is to check. Some compilers will be fairly aggressive in terms of optimising code, and others won't.

Popular pages Recent additions subscribe to a feed