ceres求解非线性方程组

参考官网和一些文档试着写下以下非线性方程组求解
除了官网文档,以下文档也值得学习:
博客1
博客2
后方交会
使用 Ceres Solver 求解非线性优化问题,主要包括以下几部分:

【STEP 1】构建优化问题(ceres::Problem)

【STEP 2】构建代价函数(ceres::CostFunction) 或残差(residual)

【STEP 3】配置代价函数和损失函数(ceres::Problem::AddResidualBlock):通过 AddResidualBlock 添加代价函数(cost function)、损失函数(loss function) 和待优化状态量

LossFunction: a scalar function that is used to reduce the influence of outliers on the solution of non-linear least squares problems.

【STEP 4】配置求解器(ceres::Solver::Options)

【STEP 5】运行求解器(ceres::Solve(options, &problem, &summary))

参考以上文档,对以下方程求解:
{ x 2 + y − 5 = 0 x + y − 3 = 0 4 x + y 2 − 9 = 0 \begin{cases} x^2+y-5=0 \\ x+y-3 = 0 \\ 4x+y^2-9 = 0 \\ \end{cases} x2+y5=0x+y3=04x+y29=0
明显有x=2,y=1

#include"ceres/ceres.h"
using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
using ceres::Solve;
struct nonline_fun 
{
	//x=2,1
    template <typename T> 
    bool operator()(const T* const x, T* residual) const {
        residual[1] = x[0]*x[0]+x[1]-T(5.0);
        residual[0] = x[0] + x[1] - T(3.0);
        residual[2] = T(4.0) * x[0] + x[1] * x[1] - T(9.0);
        return true;
    }
};
int main()
{
    Problem problem;
   //待优化参数
    double y[2]={0.0,0.0};
    //3:残差数量,2:()函数第一个参数的维度,这里是x的维度
    CostFunction* cost_function =
        new AutoDiffCostFunction<nonline_fun, 3, 2>(new nonline_fun);
    problem.AddResidualBlock(cost_function, NULL, y);
    Solver::Options options;
    options.minimizer_progress_to_stdout = true;
    Solver::Summary summary;
    Solve(options, &problem, &summary);

    std::cout << summary.BriefReport() << "\n";

    std::cout << y[0] << "\n" << y[1] << "\n";
    return 0;
}

实验结果:x=2,y=1
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值