/*CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC C C C CONTINUED FRACTION EXPANSION OF A REAL NUMBER C C 06/10/07 (DKC) C C C C This C program approximates given real numbers with rational numbers using C C the continued fraction algorithm. C C C CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC*/ #include <stdio.h> #include <math.h> void main() { double X,Y,B,MAX; unsigned int I,J; unsigned int A[21],H[21],K[21]; // printf(" CONTINUED FRACTION EXPANSION OF A REAL NUMBER \n"); MAX=65536.0; MAX=MAX*32768.0-1.0; // // REAL NUMBER // X=0.372965733829521; printf(" X=%f \n",X); // // COMPUTE THE PARTIAL QUOTIENTS // I=1; A[1]=(unsigned int)X; if((X<0.0)&&(X!=(double)A[1])) A[1]=A[1]-1; B=X-(double)A[1]; if(B<=0.0) goto L300; X=1.0/B; for (I=2; I<=20; I++) { if(X>MAX) goto L250; A[I]=(unsigned int)X; B=X-(double)A[I]; if(B<=0.0) goto L300; X=1.0/B; } I=21; L250: I=I-1; // // COMPUTE THE CONVERGENTS // L300: J=I; H[1]=A[1]; K[1]=1; Y=(double)H[1]; Y=Y/(double)K[1]; I=1; printf(" I=%d, H[I]=%d, K[I]=%d, Y=%f \n",I,H[I],K[I],Y); if(J==1) goto L500; // H[2]=A[2]*H[1]+1; K[2]=A[2]*K[1]; Y=(double)H[2]; Y=Y/(double)K[2]; I=2; printf(" I=%d, H[I]=%d, K[I]=%d, Y=%f \n",I,H[I],K[I],Y); if(J==2) goto L500; // for (I=3; I<=J; I++) { H[I]=A[I]*H[I-1]+H[I-2]; K[I]=A[I]*K[I-1]+K[I-2]; Y=(double)H[I]; Y=Y/(double)K[I]; printf(" I=%d, H[I]=%d, K[I]=%d, Y=%f \n",I,H[I],K[I],Y); } L500: return; }