0

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.

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by pyTony
0

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

0

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.

0

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
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.