Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Programm: math.C // Kleine Bibliothek mathematischer Funktionen. #include #include namespace ifm { double sqrt(double n) { // PRE: n >= 0. // POST: Gibt Approximation der Quadratwurzel // von n zurueck. assert(n >= 0); if (n == 0) return 0; // Newton-Iteration: x_{i+1} = 1/2 (x_i + n/x_i) // Wir beginnen mit einem Startwert x_0 > sqrt(n). // Wie in der Theorie verlangen wir, dass der // Approximationswert in jedem Schritt kleiner // wird. Damit terminiert das Programm, und wir // koennen sogar beweisen, dass "ungefaehr" // das richtige herauskommt double curr = n + 1; // aktueller Wert double prev; // voriger Wert do { prev = curr; assert(curr > 0); curr = (curr + n / curr) / 2; } while (curr < prev); return curr; } // double sqrt(double) } // namespace ifm