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.
It can be easily implemented in C/C++ that includes the math.h:
1 2 3 4 | inline double power(double x, double y) { return exp(y * log(x)); } |
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:
1 2 3 4 5 6 7 8 9 | 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 :) } |
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) --
loading...
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++?
you do not know what is the internal implementation of these functions.
Thanks.
I do not need to know. this article just gives you the quick implementation if you just want to know roughly the value of x^y.