Newton-Raphson Method
#include <stdio.h>
#include <math.h>
// Newton-Raphson sqrt implementation
double sqrt_newton(double x, double tolerance, int maxIter) {
if (x < 0) return NAN; // Handle negative input
if (x == 0 || x == 1) return x; // Edge cases
double y = x / 2.0; // Initial guess
for (int i = 0; i < maxIter; i++) {
double y_new = (y + x / y) / 2;
if (fabs(y_new - y) < tolerance || fabs(y_new * y_new - x) < tolerance) {
return y_new;
}
y = y_new;
}
return y;
}
// Test function
int main() {
double test_values[] = {0, 1, 2, 4, 9, 16, 25, 100, 0.25, 0.5};
int num_tests = sizeof(test_values) / sizeof(test_values[0]);
printf("Testing sqrt_newton implementation:\n");
printf("Value\t\tNewton\t\tMath sqrt\t\tDifference\n");
printf("--------------------------------------------------------\n");
for (int i = 0; i < num_tests; i++) {
double x = test_values[i];
double newton_result = sqrt_newton(x, 1e-10, 100);
double math_result = sqrt(x);
double diff = fabs(newton_result - math_result);
printf("%.6f\t\t%.10f\t\t%.10f\t\t%.2e\n",
x, newton_result, math_result, diff);
}
return 0;
}