/*
 * Program to find square root using Newton's method.
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int main(void) {

	float input;
	float threshold;
	int max_iter;

	printf("enter values for input, threshold, maximum iterations\n");
	if (scanf("%f %f %d", &input, &threshold, &max_iter) != 3) {
		printf("invalid input\n"); return EXIT_FAILURE;
	}
	if (input < 0) {
		printf("unable to compute square root of negative number\n");
		return EXIT_FAILURE;
	}

	printf("square root of %g:\n", input);

	int iter = 0;
	double current_guess = input;

	while ((iter < max_iter) && 
			(fabs(current_guess*current_guess - input) >= threshold)) {
		current_guess = 0.5 * (current_guess + input / current_guess);
		++iter;
	}

	printf("with newton's method (threshold %g):  %g (%d iterations)\n",
			threshold, current_guess, iter);
	printf("using library function:  %g\n", sqrt(input));
	printf("difference:  %g\n", current_guess - sqrt(input));

	return EXIT_SUCCESS;
}