From f388aa73d9230b16388f39b6c56f2dc79193872b Mon Sep 17 00:00:00 2001 From: Chris Laurel Date: Wed, 5 Sep 2001 21:34:19 +0000 Subject: [PATCH] Template-based root finding algorithms. --- src/solve.h | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/solve.h diff --git a/src/solve.h b/src/solve.h new file mode 100644 index 000000000..5b651a234 --- /dev/null +++ b/src/solve.h @@ -0,0 +1,36 @@ +// solve.h +// +// Copyright (C) 2001, Chris Laurel +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. + +#include + + +// Solve a function using the bisection method. Returns a pair +// with the solution as the first element and the error as the second. +template std::pair solve_bisection(F f, + T lower, T upper, + T err, + int maxIter = 100) +{ + T x = 0.0; + + for (int i = 0; i < maxIter; i++) + { + x = (lower + upper) * (T) 0.5; + if (upper - lower < 2 * err) + break; + + T y = f(x); + if (y < 0) + lower = x; + else + upper = x; + } + + return std::make_pair(x, (upper - lower) / 2); +}