Files
university/S1/GdCP/klausur_uebung/sqrtrec.c
2025-04-28 16:59:44 +02:00

32 lines
607 B
C

#include<float.h>
#include<stdio.h>
#include<math.h>
//#include "testing-0xx.h"
double sqrt_rec(double x, double p) {
// Check for edge cases
if (x == 0 || x < 0) {
return 0;
}
// Get the next element like the formula provided
double next = 0.5 * (p + x/p);
// Decide whether to go further
if (fabs(next - p) < DBL_EPSILON) {
return next;
}
// Recusrevely try the next element in the series
return sqrt_rec(x, next);
}
int main() {
printf("%f\n", sqrt_rec(2, 1));
printf("%f\n", sqrt_rec(4, 1));
printf("%f\n", sqrt_rec(8, 1));
printf("%f\n", sqrt_rec(9, 1));
}