更新时间:2022-12-07 17:23:35
Ignacio的答案已经提到使用对数.但是我们最终还是使用了exp()
,它又是一个库函数.因此,如果您根本不想使用库函数,则必须诉诸于
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
正如伊格纳西奥(Ignacio)所述,base^power = exp( power*ln(base) )
是泰勒对x^y
展开式的直接评估是乏味的.而且泰勒对e ^ x的扩展非常简单,对于 ln(x)也非常简单.两者都可以在C中简单地进行迭代/递归实现.
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
这是使用上述泰勒展开式的e^x
的简单实现方式
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);
}
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)
给出376.152869
,其中我希望,使用此示例,您可以自己实现ln(x)
.
I hope, using this example, you can implement ln(x)
on your own.