Algorithms, Blockchain and Cloud

How to Compute the Power of Arbitrary Base without Loops in C/C++?


If we want to compute , and if the y is integer, we can easily do this using a straigtforward loop O(n), or a O(logn) approach. However, if the exponential is a double, this cannot be done in this manner. However, with some mathematics proof, we can do it using just two functions, the exp to compute the and log which computes the .

after wrapped with the ln function it becomes:

and we continue by adding the exp wrapper, which becomes:

is simplified to:

there you go, with the simple/effective formula.

power-x-y-formula

It can be easily implemented in C/C++ that includes the math.h:

inline 
double power(double x, double y) {
    return exp(y * log(x));
}

This article just gives you the quick implementation if you just want to know roughly the value of . However, it depends on how the functions exp and log are implemented in the system library math.h but these are quite standard and are defined and well implemented in ANSI C/C++, so there is nothing to worry about.

How is it compared to the pow() function in C/C++? Is it faster? Is it numerically stable? We have to run some tests before coming to a conclusion. The implementation of pow() may look like this:

double pow(double x, double y) {
   if (abs((int)y - y) < EPS) { // if y is integer
      return power(x, (int)y) ; // speed up if y is integer
   }
   if (y < 0) {
      return 1.0 / power(x, -y); // e.g. 2^(-1) = 1.0/(2^1)
   }
   return power(x, y); // use the above implementation :)
}

--EOF (The Ultimate Computing & Technology Blog) --

649 words
Last Post: How to Read File Content from URL with Time out in PHP?
Next Post: How to Compute Minkowski, Euclidean and CityBlock Distance in C++?

The Permanent URL is: How to Compute the Power of Arbitrary Base without Loops in C/C++? (AMP Version)

Exit mobile version