我的自然对数连分数算法有问题。我需要在 6 次迭代中以 1e-6 的精度计算自然对数,例如 ln(0.31),我的算法将在 8 次中完成。
这是我的实现:
#include<stdio.h>
#include<math.h>
#include<string.h>
double c_frac_log(double x, unsigned int n)
{
double z=(x-1)/(x+1);
double zz = z*z,res=0;
double cf = 1;
for (int i = n; i >= 1; i--)
{
cf = (2*i-1) - i*i*zz/cf;
}
res=2*z/cf;
return res;
}
int c_frac_eps(double x,double eps)
{
int a=0;
double loga=log(x),fraclog=c_frac_log(x,a);
double roz=(loga-fraclog);
roz=fabs(roz);
for(a=0;roz >= eps;a++)
{
fraclog=c_frac_log(x,a);
roz=(loga-fraclog);
roz=fabs(roz);
}
return a-1;
}
int main()
{
double x=0.31,eps=0.000001;
printf("c_frac_log (%0.4f) =%0.12f \n",x,c_frac_log(x,c_frac_eps(x,eps)));
printf("math.h - log(%0.4f)=%0.12f\n",x,log(x));
printf("minimum of iterations with accuracy %f is %d\n",eps,c_frac_eps(x,eps));
return 0;
}
你们中有人知道如何改进我的代码吗?