Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast implementation/approximation of pow() function in C/C++

Tags:

c++

c

math

gcc

numeric

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)

like image 809
zoli2k Avatar asked Feb 04 '23 05:02

zoli2k


2 Answers

Here are some approxmiations:

  • Optimized pow Approximation for Java and C / C++. This approximation is very inaccurate, you have to try for yourself if it is good enough.
  • Optimized Exponential Functions for Java. Quite good! I use it for a neural net.

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.

like image 198
martinus Avatar answered Feb 05 '23 20:02

martinus


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

like image 23
Alex Jenter Avatar answered Feb 05 '23 20:02

Alex Jenter