Stellarium  0.16.1
Solve.hpp
1 // Solve.hpp
2 //
3 // Copyright (C) 2001, Chris Laurel <claurel@shatters.net>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
9 //
10 // 2008-06-28 - reformatted to comply with Stellarium's coding
11 // style -MNG
12
13
14 #ifndef _SOLVE_HPP_
15 #define _SOLVE_HPP_
16
17 #include <utility>
18
19 // Solve a function using the bisection method. Returns a pair
20 // with the solution as the first element and the error as the second.
21 template<class T, class F> std::pair<T, T> solveBisection(F f,
22  T lower, T upper,
23  T err,
24  int maxIter = 100)
25 {
26  T x = 0.0;
27
28  for (int i = 0; i < maxIter; i++)
29  {
30  x = (lower + upper) * (T) 0.5;
31  if (upper - lower < 2 * err)
32  break;
33
34  T y = f(x);
35  if (y < 0)
36  lower = x;
37  else
38  upper = x;
39  }
40
41  return std::make_pair(x, (upper - lower) / 2);
42 }
43
44
45 // Solve using iteration; terminate when error is below err or the maximum
46 // number of iterations is reached.
47 template<class T, class F> std::pair<T, T> solveIteration(F f,
48  T x0,
49  T err,
50  int maxIter = 100)
51 {
52  T x = 0;
53  T x2 = x0;
54
55  for (int i = 0; i < maxIter; i++)
56  {
57  x = x2;
58  x2 = f(x);
59  if (abs(x2 - x) < err)
60  return std::make_pair(x2, x2 - x);
61  }
62
63  return std::make_pair(x2, x2 - x);
64 }
65
66
67 // Solve using iteration method and a fixed number of steps.
68 template<class T, class F> std::pair<T, T> solveIteration_fixed(F f,
69  T x0,
70  int maxIter)
71 {
72  T x = 0;
73  T x2 = x0;
74
75  for (int i = 0; i < maxIter; i++)
76  {
77  x = x2;
78  x2 = f(x);
79  }
80
81  return std::make_pair(x2, x2 - x);
82 }
83
84 #endif // _SOLVE_HPP_
85