Ignacio's answer already mentions using logarithms. But we ultimately end up using exp()
which again is a library function. So if you don't want to use library functions at all, then you have to resort to something like Taylor's expansion of x^y
As direct evaluation of Taylor's expansion for x^y
is tedious, as Ignacio mentioned, base^power = exp( power*ln(base) )
. And taylor's expansion for e^x is quite simple and that for ln(x) is also very simple. Both of them yield for simple interative/recursive implementation in C
Here is a simple implementation of e^x
using the above Taylor's expansion
double pow_x ( double x , unsigned i )
{
double prod=1;
if ( i == 0 )
return 1;
while ( i )
{
prod*=x;
i--;
}
return prod;
}
long long factorial ( unsigned n )
{
if ( n == 0 )
return 1;
return n * factorial (n-1);
}
// Function to calculate e^x. Hence expo(5, 20) is calculating
// e^5 by summing 20 terms from the infinite series expansion
// and NOT a power calculation of 5^20
double expo ( double x, int terms )
{
/* terms tells us how long should we expand the taylor's series */
double sum=0;
unsigned i=0;
while ( i< terms )
{
sum+= pow_x(x,i)/factorial(i);
i++;
}
return sum;
}
exp(5.93,20)
gives 376.152869
which Google tends to agree.
I hope, using this example, you can implement ln(x)
on your own.