using dFun = function<double(const double&)>; using cdouble = const double; cdouble TOLERANCE = 0.00001; bool CloseEnough (cdouble &val1, cdouble &val2) { return (abs(val1 - val2) < TOLERANCE); } double FixedPoint (dFun f, cdouble &guess) { const auto next = f (guess); if (CloseEnough (guess, next)) { return next; } else { return FixedPoint (f, next); } } dFun AverageDamp (dFun f) { return [f] (cdouble &x) {return (x + f(x)) / 2;}; } double Sqrt (cdouble &x) { return FixedPoint (AverageDamp( [x] (cdouble &y) {return (x / y); }) , 1.0); } int main () { cout << Sqrt(121.0); cout << endl; return 0; }
时间: 2024-11-13 15:26:57