コード例 #1
0
/**
In this formulation of the Multi-Dimensional Newton-Raphson solver the Jacobian matrix is known.
Therefore, the dx vector can be obtained from

J(x)dx=-f(x)

for a given value of x.  The pointer to the class FuncWrapperND that is passed in must implement the call() and Jacobian()
functions, each of which take the vector x. The data is managed using std::vector<double> vectors

@param f A pointer to an subclass of the FuncWrapperND class that implements the call() and Jacobian() functions
@param x0 The initial guess value for the solution
@param tol The root-sum-square of the errors from each of the components
@param maxiter The maximum number of iterations
@param errstring  A string with the returned error.  If the length of errstring is zero, no errors were found
@returns If no errors are found, the solution.  Otherwise, _HUGE, the value for infinity
*/
std::vector<double> NDNewtonRaphson_Jacobian(FuncWrapperND *f, std::vector<double> &x0, double tol, int maxiter)
{
    int iter=0;
    f->errstring.clear();
    std::vector<double> f0,v;
    std::vector<std::vector<double> > JJ;
    Eigen::VectorXd r(x0.size());
    Eigen::Matrix2d J(x0.size(), x0.size());
    double error = 999;
    while (iter==0 || std::abs(error)>tol){
        f0 = f->call(x0);
        JJ = f->Jacobian(x0);
        
        for (std::size_t i = 0; i < x0.size(); ++i)
        {
            r(i) = f0[i];
            for (std::size_t j = 0; j < x0.size(); ++j)
            {
                J(i,j) = JJ[i][j];
            }
        }

        Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r);

        // Update the guess
        for (std::size_t i = 0; i<x0.size(); i++){ x0[i] += v(i);}
        
        // Stop if the solution is not changing by more than numerical precision
        if (v.cwiseAbs().maxCoeff() < DBL_EPSILON*100){
            return x0;
        }
        error = root_sum_square(f0);
        if (iter>maxiter){
            f->errstring = "reached maximum number of iterations";
            x0[0] = _HUGE;
        }
        iter++;
    }
    return x0;
}