#include <stdio.h>
#include <math.h>
double sqrt_binary_search(double S) {
if (S < 0) return NAN;
if (S == 0) return 0;
double low = 0, high = S, mid;
double threshold = 1e-7;
while (high - low > threshold) {
mid = (low + high) / 2;
if (mid * mid < S) {
low = mid;
} else {
high = mid;
}
}
return mid;
}
int main() {
double number = 25;
printf("The square root of %f is %f\n", number, sqrt_binary_search(number));
return 0;
}
|