1. ## Program not working

Hello I wrote this program to find the square root of any number that the user enters using newtons method but it is not working. The initial guess is the number entered by the user divided by 10. And after running through equation and calculating the new value it compares it with the old value(xm1) and if the difference between them is less then 0.001 then it prints out the value it calculated. I would be very greatful if someone can corrent my mistake or point out to me where I made the mistake.

Code:
```#include <stdio.h>
#include <math.h>

#define SIZE 5

int main()
{
float x, number,xm1,r;
float difference;
int a;

printf("Please enter the number of which you wish the square root of: ");
scanf("%f",&number);

a=number/2;
xm1=0;
difference = 1;

x = a - (pow(a,2)-number)/(2*a);
xm1=x;

while(difference >= 0.01)
{
r=  xm1- (pow(xm1,2)-number)/(2*xm1);

difference = r-xm1;

xm1=r;

}

if(difference <= 0.01)
{
printf("the square root is %f\n",r);
}

return 0;
}```

2. One problem you are going to run into is precision. Comparing floating point numbers is fraught with difficulties. There are a number of links in this post that have material devoted to floating point numbers.

3. I'm assuming the problem you're running into (you forgot to mention what it was) is that you failed to compare fabs(difference) to 0.001, rather than just difference?

4. How am I meant to do that I thought that it keeps in the while loop until the difference is <= 0.01. So where am I exactly going wrong becasue I don't understand what you are saying.

5. What is your actual problem?
The newton's method of finding square roots yields approximate results and should be expected.
Edit:
It looks like your initial guess plays a major role in how approximate the result would be.
The initial guess is the number entered by the user divided by 10
I think you meant 2.

6. Originally Posted by HAssan
How am I meant to do that I thought that it keeps in the while loop until the difference is <= 0.01. So where am I exactly going wrong becasue I don't understand what you are saying.
So what if the difference is -12345578? That's less than 0.01, but you sure as heck don't want to stop. You need to check whether the absolute value of the difference is less than 0.01.