Friday, April 08, 2011

exp(y*log(x)) Much Faster than Math.pow(x,y)

Today I found out that replacing Math.pow(x,y) by Math.exp(y*Math.log(x)) made me gain 50% performance in my program. Of course, both x and y are double in my case. I find this quite surprising, I expected better from Math.pow.

3 comments :

  1. pow is more than just exp and log called one after the other:
    1) it handles cases where x is negative (and can return negative values, unlike exp),
    2) log "compresses" values into a smaller range, which gets extended again by exp: you lose accuracy in this operation, and pow takes care of it, doing more accurate computations.

    If you are doing intensive math calculations and approximated results are enough for you, you might want to try http://sourceforge.net/projects/jafama.

    ReplyDelete
  2. pow is more than just exp and log called one after the other:
    1) it handles cases where x is negative (and can return negative values, unlike exp),
    2) log "compresses" values into a smaller range, which gets extended again by exp: you lose accuracy in this operation, and pow takes care of it, doing more accurate computations.

    If you are doing intensive math calculations and approximated results are enough for you, you might want to try http://sourceforge.net/projects/jafama.

    ReplyDelete
  3. I did not know about jafama. If you look at their pow implementation, it does exp(y log x), using their own exp and log.

    http://jafama.svn.sourceforge.net/viewvc/jafama/src/odk/lang/FastMath.java?revision=3&view=markup

    ReplyDelete