#include #include #define PRECISION 0.0001 /* Per calcolare la radice quadrata di x: Sia approx = 1 Sia precision = 0.001 Ripeti fino a quando |approx^2 - x| < precision: approx = (approx + x/approx)/2 Esci e ritorna approx */ double my_abs(double x) { if (x >= 0) { return x; } else { return -x; } } double square(double x) { return x * x; } double average(double x, double y) { return (x + y) / 2; } // ----------------------------- int good_enough(double approx, double x) { if (my_abs(square(approx) - x) < PRECISION) { return 1; } else { return 0; } } double improve_approximation(double approx, double x) { return average(approx, x / approx); } double square_root(double x) { double approx = 1.0; while (!(good_enough(approx, x))) { approx = improve_approximation(approx, x); } return approx; } // ----------------------------- void test() { int numbers_to_test[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int length = sizeof(numbers_to_test)/sizeof(int); for (int i = 0; i < length; i++) { double number = (double) numbers_to_test[i]; double our_square_root = square_root(number); double c_square_root = sqrt(number); double difference = my_abs(our_square_root - c_square_root); if (difference > PRECISION) { printf("La radice di %f non è stata calcolata con la precisione voluta, difference=%f\n", number, difference); } } } // ----------------------------- int main(int argc, char **argv) { // -- for testing // test(); double x; printf("Calcola la radice di: "); if (scanf("%lf", &x) != 1) { printf("[ERROR] - L'input dato non è un numero, riprovare!\n"); return -1; } double root = square_root(x); printf("La radice di %0.3f è %f\n", x, root); return 0; }