October 1st, 2013, 06:13 AM
Using Newton's method to compute square root of a value
In this project, I am trying to create a program which would equate the square root of a provided positive integer using Newton's method. A screenshot to how this is done is attached to this post.
x is the provided input, and y has an initial arbitrary value of 1. The program is supposed to terminate when the difference between the old value of y and the new value of y is less than the product of 0.00001 and y. Here's the code I have written:
But when executed, the program simply freezes after entering the input. The cursor drops to a new line and just keeps blinking. What am I doing wrong here?
double y = 1, evaluation;
printf("Enter a positive number: ");
evaluation = ((y + (x / y)) / 2);
y = evaluation;
} while (evaluation > (0.00001 * y));
printf("\nSquare root: %lf", fabs(y));
October 1st, 2013, 06:49 AM
Rather than explain you problem at once, I prefer to offer you debugging your program. This is quite important skill :)
Or at least insert another printf inside the loop, printing out current values of variables. I think this will give you a hint.
Funny enough, I added similar task to my website only two days ago:
Square Root at http://codeabbey.com
Though perhaps some hint could be necessary. Check your loop exiting condition very thoroughly.
And get rid of "evaluation" variable since you assign it to y again.
Really, think twice over this strange idea the new value of y is less than the product of 0.00001 and y - could it really happen in your code?