I am writing a program to find the square root of a number. I am using the Newton-Raphson method..Just to clarify a bit of the code.. fabs(1/(x+1)) < 0.001 is to check for relative error..
EXAMPLE: for user entry of 100 if the iteration process ends in 10.055 the answer will return as 10 which is correct. But it isn't doing that.
It compiles I then proceed to run it..prompts me "Enter a number to find the square root of: I type 100 then hit enter...
"The square root of 100 is -1077834936"
Lol could you give me a bit of guidance here..thanks. My first time writing a program from complete scratch.
And I know there is a sqrt() function...just wanted to write my own.
Thanks a lot
Code:
#include <stdio.h>
#include <math.h>
double mysqrt(double a);
int main()
{
double a, result;
printf("Enter a number to find the square root of: ");
scanf("%d", &a);
result = mysqrt(a);
printf("The square root of %d is %d \n", a, result);
return 0;
}
double mysqrt(double a)
{
double x, new_x;
for(x=2; x != a;)
{
new_x=(x+1);
new_x=(0.5*(x+(a/x)));
x=new_x;
if(fabs(1/(x+1))<0.001)
{
return new_x;
}
}
}