Exponentiation in most modern languages is easy .. I use the common operator for that in my language of choice or whatever function that compensates that to get the desired functionality.
I want to know, how does this exactly work ?
The following algorithm in C is often used to demonstrate this effect ..
double exp(val, pow) {
for(int i = 0; i < pow; ++i)
val *= val;
return val;
} // exp(2, 3) -> 8
However, there is a serious bug here .. What if pow is 2.6 ? That would return 8 also ..
That's simply because the loop condition only compares the two numbers ..
But when I do something like this, it works well ..
#include <math.h>
int main() {
printf("The result of 2 to the power of 2.6 is %.2f", pow(2, 2.6));
}
How can the latter behavior be achieved ?
According to the answers, it seems the taylor expansion algorithm is the key to exponentiation, so .. what about multiplication ? How can decimal multiplication be achieved ?
Exponentiation is usually implemented as (lots of special cases plus) a reduction to exp. If you have an exp function and its inverse ln handy, you can compute x^y as
exp(y*ln(x))
But you might wonder how exp is implemented. For small arguments, the series expansion works well:
exp(x) = 1 + x + x^2/2 + x^3/6 + x^4/24 + ...
Edit: This is the Taylor expansion referred to in the other answers.
For larger values there are argument reduction techniques that can be used to compute the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With