ergo
bisection.h
Go to the documentation of this file.
1 /* Ergo, version 3.7, a program for linear scaling electronic structure
2  * calculations.
3  * Copyright (C) 2018 Elias Rudberg, Emanuel H. Rubensson, Pawel Salek,
4  * and Anastasia Kruchinina.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  *
19  * Primary academic reference:
20  * Ergo: An open-source program for linear-scaling electronic structure
21  * calculations,
22  * Elias Rudberg, Emanuel H. Rubensson, Pawel Salek, and Anastasia
23  * Kruchinina,
24  * SoftwareX 7, 107 (2018),
25  * <http://dx.doi.org/10.1016/j.softx.2018.03.005>
26  *
27  * For further information about Ergo, see <http://www.ergoscf.org>.
28  */
29 
36 #ifndef MAT_BISECTION
37 #define MAT_BISECTION
38 #include <cmath>
39 namespace mat {
47  template<typename Treal>
48  inline int sign(Treal value) {
49  if (value > 0)
50  return 1;
51  else if (value < 0)
52  return -1;
53  else
54  return 0;
55  }
56 
57 
69  template<typename Treal, typename Tfun>
70  Treal bisection(Tfun const & fun, Treal min, Treal max, Treal const tol) {
71  int sign_min = sign(fun.eval(min));
72  int sign_max = sign(fun.eval(max));
73  if (sign_min == sign_max)
74  throw Failure("bisection(Tfun&, Treal, Treal, Treal): interval "
75  "incorrect");
76  Treal middle = (max + min) / 2;
77  int sign_middle = sign(fun.eval(middle));
78  while (template_blas_fabs(max - min) > tol * 2 && sign_middle != 0) {
79  if (sign_middle == sign_min) {
80  min = middle;
81  sign_min = sign_middle;
82  }
83  else { /* (sign_middle == sign_max) */
84  max = middle;
85  sign_max = sign_middle;
86  }
87  middle = (max + min) / 2;
88  sign_middle = sign(fun.eval(middle));
89  }
90  return middle;
91  }
92 
93 } /* end namespace mat */
94 #endif
Treal bisection(Tfun const &fun, Treal min, Treal max, Treal const tol)
Bisection algorithm for root finding.
Definition: bisection.h:70
Definition: allocate.cc:39
Treal template_blas_fabs(Treal x)
#define max(a, b)
Definition: integrator.cc:87
int min(int a, int b)
Definition: lin_trans.cc:66
Definition: Failure.h:57
int sign(Treal value)
Sign function returns the sign of the input.
Definition: bisection.h:48