9

I m looking for a faster implementation or good a approximation of functions provided by cmath.

I need to speed up the following functions

  1. pow(x,y)
  2. exp(z*pow(x,y))

where z<0. x is from (-1.0,1.0) and y is from (0.0, 5.0)

zoli2k
  • 3,388
  • 4
  • 26
  • 36
  • 3
    Are you looking for something like this? http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/ – Swiss Feb 27 '10 at 11:57
  • 7
    Negative values of x?!? Get real, man! – edgar.holleis Feb 27 '10 at 12:13
  • @Shakov: Use inline assembler to do this? but, for negative values of z and x.... – t0mm13b Feb 27 '10 at 12:23
  • edgar.holleis: Example: -0.1^2.0 – zoli2k Feb 27 '10 at 12:29
  • 1
    You'll have to decide (and post here, if you can) how much of the accuracy and of space you are willing to give up for speed. How big a table can you hold? What's the relative precision you need? How much of a speed-up you must have? – AVB Feb 27 '10 at 14:34
  • @shakov - that only works for integral values of y. If you have that constraint then a speedup is simple. Document this in your question. – Hans Passant Feb 27 '10 at 14:35
  • How portable does the solution need to be ? If a certain CPU family can be assumed then there may be some CPU-specific optimisation possibilities, e.g. SIMD etc. It would also help to know how much accuracy you are looking for. – Paul R Feb 27 '10 at 17:34
  • Is y a floating point type or integer? – Mark B Feb 27 '10 at 18:36

3 Answers3

8

Here are some approxmiations:

If the above approximation for pow is not good enough, you can still try to replace it with exponential functions, depending on your machine and compiler this might be faster:

  1. x^y = e^(y*ln(x))
  2. And the result: e^(z * x^y) = e^(z * e^(y*ln(x)))

Another trick is when some parameters of the formula do not change often. So if e.g. x and y are mostly constant, you can precalculate x^y and reuse this.

martinus
  • 17,736
  • 15
  • 72
  • 92
4

What are the possible values of x and y? If they are within reasonable bounds, building some lookup tables could help.

Alex Jenter
  • 4,324
  • 4
  • 36
  • 61
  • I guess this question fits in the original question's comments section rather. – legends2k Feb 27 '10 at 11:49
  • reverting down vote. I think it's a perfectly reasonable answer. If pow is a bottleneck and you have a required accuracy down to e-6 then precalculation might be the way to go. I do this a lot and not just with pow. – Martin Feb 27 '10 at 14:10
2

I recommend the routines in the book "Math Toolkit for Real-Time Programming" by Jack W. Crenshaw.

You might also want to post some of your code to show how you are calling these functions, as there may be some other higher level optimisation possibilities that are not apparent from the description given so far.

Paul R
  • 208,748
  • 37
  • 389
  • 560