24 virtual std::pair<T, T> Initialize() = 0;
26 virtual std::pair<T, T> Iterate() = 0;
28 virtual std::pair<T, T>
Solve( T user_x_lower, T user_x_upper )
31 x_lower = user_x_lower;
32 x_upper = user_x_upper;
33 x = ( x_lower + x_upper ) / 2.0;
35 auto root = Initialize();
44 if ( !( iter % 50 ) ) printf(
"iter %4lu f(x) %E\n", iter, root.second );
45 }
while ( !Terminate( iter, root, previous ) );
56 void SetupTerminationCriteria(
size_t niter, T tol )
58 this->use_defined_termination_criteria =
true;
63 bool ReachMaximumIteration(
size_t iter )
65 return ( iter < niter );
68 bool Terminate(
size_t iter, std::pair<T, T> &now, std::pair<T, T> &previous )
70 bool doterminate =
false;
71 if ( std::fabs( now.second ) < std::numeric_limits<T>::epsilon() )
76 if ( use_defined_termination_criteria )
78 if ( iter >= niter ) doterminate =
true;
79 if ( std::fabs( ( now.second - previous.second ) / previous.second ) < tol )
87 bool use_defined_termination_criteria =
false;
99 template<
typename FUNC,
typename T>
111 T &x_lower = this->x_lower;
112 T &x_upper = this->x_upper;
115 f_lower = func->F( x_lower );
116 f_upper = func->F( x_upper );
119 if ( ( f_lower < 0.0 && f_upper < 0.0 ) || ( f_lower > 0.0 && f_upper > 0.0 ) )
121 printf(
"endpoints do not straddle y = 0\n" );
126 std::pair<T, T> root( ( x_lower + x_upper ) / 2.0, ( f_lower + f_upper ) / 2.0 );
134 T x_bisect, f_bisect;
136 T &x_lower = this->x_lower;
137 T &x_upper = this->x_upper;
139 if ( f_lower == 0.0 )
return std::pair<T, T>( x_lower, f_lower );
140 if ( f_upper == 0.0 )
return std::pair<T, T>( x_upper, f_upper );
143 x_bisect = ( x_lower + x_upper ) / 2.0;
144 f_bisect = func->F( x_bisect );
145 if ( f_bisect == 0.0 )
149 return std::pair<T, T>( x_bisect, f_bisect );
153 if ( ( f_lower > 0.0 && f_bisect < 0.0 ) || ( f_lower < 0.0 && f_bisect > 0.0 ) )
157 return std::pair<T, T>( 0.5 * ( x_lower + x_upper ), f_upper );
163 return std::pair<T, T>( 0.5 * ( x_lower + x_upper ), f_lower );
180 template<
typename FUNC,
typename T>
192 T x_bisect, f_bisect, df_bisec;
194 T &x_lower = this->x_lower;
195 T &x_upper = this->x_upper;
197 if ( !func->HasdF() )
199 printf(
"Newton(): no first order derivity provided\n" );
203 x_bisect = ( x_lower + x_upper ) / 2.0;
204 f = func->F( x_bisect );
205 df = func->dF( x_bisect );
208 std::pair<T, T> root( x_bisect, f );
219 printf(
"Newton(): derivative is zero\n" );
220 return std::pair<T, T>( x, f );
226 if ( func->HasFdF() )
228 auto fdf = func->FdF( x );
240 printf(
"Newton(): f( x ) is infinite\n" );
245 printf(
"Newton(): f'( x ) is infinite\n" );
248 return std::pair<T, T>( x, f );
This is not thread safe.
Definition: root.hpp:100
std::pair< T, T > Initialize()
Definition: root.hpp:109
std::pair< T, T > Iterate()
Definition: root.hpp:132
std::pair< T, T > Initialize()
Definition: root.hpp:190
std::pair< T, T > Iterate()
Definition: root.hpp:213
virtual std::pair< T, T > Solve(T user_x_lower, T user_x_upper)
Definition: root.hpp:28