The C program computes the rational approximation to a given real number, i.e., given a real number val, the program computes a pair of integers N and D such that the fraction N/D is a good approximation to val. To do so, we use the following series of steps.
• Take a guess integer value for N.
• Find D by rounding off (N/val).
• Compute the difference between val and N/D. If the difference is less than the specified value, print the values of N and D.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define NMAX 1000000
int main()
{
unsigned long num,den;
double val,error,delta;
int nsig;
clrscr();
val=acos(-1.0); /* val =pi for our example*/
nsig=6;
delta=1.0/pow(10.0,nsig);
printf("\n Finding rational approx. to %17.15lf",val);
printf("\n correct to %d significant places\n",nsig);
for(num=1;num<=NMAX;num++)
{
den= num/val+0.5;
error=fabs(1.0-num/(den*val));
if(error<=delta)
{
printf("\n %ld/%ld = %17.15lf for %17.15lf",num,den,(double)num/den,val);
nsig=-log10(error);
printf("\n Correct to %d significant digits",nsig);
break;
}
}
getch();
return 0;
}
Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Related Articles
Basic Courses
Advance Courses