Hi all,

I have written a program to find the reciprocal of an input number by using newton rhapson iterative method. Below is the algorithm implementation in C:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
double guess,newguess,input,error=1.0;                                       
printf("Enter the input number");
scanf("%f",&input);
printf("Enter the guess for the reciprocal of the input number between -1.0 and 1.0");
scanf("%f",&guess);
while(error>0.0001)
{
         newguess=guess*(2-(input*guess));
         error=newguess-guess;
         guess=newguess;
}
printf("The reciprocal of the input number is %f",newguess);
system("pause");
return 0;
}

When I enter 3 as my input number, i get an absurd answer. On using hand-calculations on paper, I am converging to the right value of the reciprocal which is .33. Kindly point out the errors. Thank you.

At lines 8 and 10, use %lf (small L) instead of %f.

OR, line 6, change double to float.

Your algorithm is still producing rubbish result for 123123, guess 0.1, even when correcting the missing absolute value for error.

I have corrected my code. Here's the modified version:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float guess,newguess,input,error=1;                                       
printf("Enter the input number");
scanf("%f",&input);
printf("Enter the guess for the reciprocal of the input number between -1.0 and 1.0");
scanf("%f",&guess);
while(error>0.0001)
{
         newguess=guess*(2-(input*guess));
         error=newguess-guess;
         guess=newguess;
}
printf("The reciprocal of the input number is %f",newguess);
system("pause");
return 0;
}

This works perfectly.

Hmmm... really?

Enter the input number123123
Enter the guess for the reciprocal of the input number between -1.0 and 1.0.1
The reciprocal of the input number is -1231.030029
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.