I have problem with my continued fraction algorithm for natural logarithm. I need to calculate natural logarithm for example ln(0.31) with accuracy on 1e-6 in 6 iterations, my algorithm will do it in 8.
This is my implementation:
#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;
}
Do any of you have some idea how to refine my code?
The initial
cf
affects the end result - a little bit.In a previous comment, found that
cf = 1.88*n-0.95;
yielded a better result thandouble cf = 1;
This was found by reversing the algorithm and finding a correlation with
n
. YMMV.Original results
With this change
6 beats 8 and meets OP's "in 6 iterations".
Note: type consistency: