Floating exponent exponentiation algorithm
-
09-10-2019 - |
Question
I must to write a algorithm that exponentiates a base (integer or float) in a integer or float argument. I wrote this algorithm for Deluge (zoho.com), but it can only use integer exponents:
float math.potencia(float base, int expoente)
{
if(expoente>0)
{
base = base * thisapp.math.potencia(base, (input.expoente - 1));
}
else if (expoente == 0)
{
base = 1;
}
return base;
}
(Deluge doesn't have a potentiation operator or function). Thanks!
Solution 2
Well, more than 17 hours without a reply, finally I've found an answer to my own question:
In the simplest way, we can solve the problem using the value of "e" exponentiating to the logarithm of the number divided by the index:
e^(Log(number)/index)
where number is the radicand and index is the desired root.
Eg: The 10th root of the number 1024: e^(Log(1024)/10) = 2.
PS: the base of the Log function is also "e". the rounded value for "e" is: 2.718281828459045
I hope this technique may be usefull for you.
OTHER TIPS
Suppose that you can use sqrt, you can use the following algorithm:
double EPS = 0.0001;
double exponentiation(double base, double exp){
if(exp >= 1){
double temp = exponentiation(base, exp / 2);
return temp * temp;
} else{
double low = 0;
double high = 1.0;
double sqr = sqrt(base);
double acc = sqr;
double mid = high / 2;
while(abs(mid - exp) > EPS){
sqr = sqrt(sqr);
if (mid <= exp) {
low = mid;
acc *= sqr;
} else{
high = mid;
acc *= (1/sqr);
}
mid = (low + high) / 2;
}
return acc;
}
}