Stellarium 0.13.2
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 "config.h"
18 
19 #include <utility>
20 
21 // Solve a function using the bisection method. Returns a pair
22 // with the solution as the first element and the error as the second.
23 template<class T, class F> std::pair<T, T> solveBisection(F f,
24  T lower, T upper,
25  T err,
26  int maxIter = 100)
27 {
28  T x = 0.0;
29 
30  for (int i = 0; i < maxIter; i++)
31  {
32  x = (lower + upper) * (T) 0.5;
33  if (upper - lower < 2 * err)
34  break;
35 
36  T y = f(x);
37  if (y < 0)
38  lower = x;
39  else
40  upper = x;
41  }
42 
43  return std::make_pair(x, (upper - lower) / 2);
44 }
45 
46 
47 // Solve using iteration; terminate when error is below err or the maximum
48 // number of iterations is reached.
49 template<class T, class F> std::pair<T, T> solveIteration(F f,
50  T x0,
51  T err,
52  int maxIter = 100)
53 {
54  T x = 0;
55  T x2 = x0;
56 
57  for (int i = 0; i < maxIter; i++)
58  {
59  x = x2;
60  x2 = f(x);
61  if (abs(x2 - x) < err)
62  return std::make_pair(x2, x2 - x);
63  }
64 
65  return std::make_pair(x2, x2 - x);
66 }
67 
68 
69 // Solve using iteration method and a fixed number of steps.
70 template<class T, class F> std::pair<T, T> solveIteration_fixed(F f,
71  T x0,
72  int maxIter)
73 {
74  T x = 0;
75  T x2 = x0;
76 
77  for (int i = 0; i < maxIter; i++)
78  {
79  x = x2;
80  x2 = f(x);
81  }
82 
83  return std::make_pair(x2, x2 - x);
84 }
85 
86 #endif // _SOLVE_HPP_
87