ceres-solver / ceres-solver

A large scale non-linear optimization library
http://ceres-solver.org/
Other
3.87k stars 1.04k forks source link

Minimizing a generic quadratic function #374

Closed SubMishMar closed 6 years ago

SubMishMar commented 6 years ago

The tutorial lucidly explains how to minimize a simple quadratic function like 0.5(10-x)^2. But how can I do it for lets say 0.5(x^2 + 3*x + 1)? I modified the code as follows:

struct CostFunctor{  
    template <typename T>  
    bool operator() (const T* const x, T* residual) const {  
        residual[0] = sqrt(x[0]*x[0] + T(3.0) * x[0] + T(1.0));  
        return true;  
    }  
};

But I the following compilation error:

error: call of overloaded ‘sqrt(double)’ is ambiguous

I understand that sqrt() normally doesnt take in templates as inputs but I dont know how to make this work. Any help will be appreciated. Thanks.

sergiud commented 6 years ago

Why do you call sqrt in the first place? Other than that, you probably need to insert a using std::sqrt prior to its use.

SubMishMar commented 6 years ago

I have tried std::sqrt, it does compile but the solver complains that the residual is not correct.

I use sqrt because I want to minimize x^2+3x+1 if I set the residual without sqrt, it will minimize x^2+3x+1 and it's not the same thing.

sergiud commented 6 years ago

I use sqrt because I want to minimize x^2+3x+1 if I set the residual without sqrt, it will minimize x^2+3x+1 and it's not the same thing.

I'm sorry, but this does not make any sense.

sandwichmaker commented 6 years ago

@SubMishMar The nonlinear least squares minimizer cannot minimize arbitrary quadratic functions. It can only minimize functions that can be written as the sum of squares. If you want to minimize arbitrary functions, I recommend using the Gradient based solver.

SubMishMar commented 6 years ago

@sandwichmaker Thanks for the clarification. Btw, Can I solve a linear system like Ax = b in ceres?