00001 #ifndef NEWTONNONLINEARSOLVER_H
00002 #define NEWTONNONLINEARSOLVER_H
00003
00004 namespace Flash
00005 {
00006
00007 template<typename Function, typename FunctionPrime>
00008 double NewtonRaphson(Function function, FunctionPrime derivative, double initialGuess, double tolerance = 1.0E-4, unsigned maxIterations = 100)
00009 {
00010
00011 double xNew = 0.0;
00012 double xOld = initialGuess;
00013
00014 for(unsigned iter = 0; iter < maxIterations; ++iter)
00015 {
00016 xNew = xOld - function(xOld) / derivative(xOld);
00017
00018 if(fabsf(xNew - xOld)/xNew < tolerance) break;
00019
00020 xOld = xNew;
00021 }
00022
00023 return xNew;
00024 }
00025
00026
00027 template<typename Function>
00028 double NewtonRaphson(Function function, double initialGuess, double tolerance = 1.0E-4, unsigned maxIterations = 100)
00029 {
00030
00031 double xNew = 0.0;
00032 double xOld = initialGuess;
00033 const double epsilon = 1.0E-6;
00034
00035 for(unsigned iter = 0; iter < maxIterations; ++iter)
00036 {
00037 xNew = xOld - 2.0 * epsilon * function(xOld) / (function(xOld + epsilon) - function(xOld - epsilon));
00038
00039 if(fabsf(xNew - xOld)/xNew < tolerance) break;
00040
00041 xOld = xNew;
00042 }
00043
00044 return xNew;
00045 }
00046 }
00047
00048 #endif