如何用Eigen::AutoDiffScalar检索微分结果

How to retrive differentiation results with Eigen::AutoDiffScalar

本文关键字:结果 检索 AutoDiffScalar 何用 Eigen      更新时间:2023-10-16

我正在学习使用这个库。试图微分一个简单的函数,y = x^2,不会得到预期的结果(x = 8dy/dx = 2x = 16)。

#include <eigen3/Eigen/Core>
#include <eigen3/unsupported/Eigen/AutoDiff>
#include <iostream>
int main(int argc, char *argv[])
{
  Eigen::AutoDiffScalar<Eigen::Vector2d> x(8.0), y;
  y = x*x;
  std::cout << y.derivatives()[0];
  return 0;
}

您声明的标量实际上就是一个标量,因此您正在查找标量(8*8)的导数,即0。为了表明8是第一个变量的值,您需要将它的一阶导数设置为1:

#include <eigen3/Eigen/Core>
#include <eigen3/unsupported/Eigen/AutoDiff>
#include <iostream>
int main(int argc, char *argv[])
{
  // Note different initialization
  Eigen::AutoDiffScalar<Eigen::Vector2d> x(8.0, Eigen::Vector2d(1,0)), y;
  y = x*x;
  std::cout << "x = " << x << "n"
            << "y = " << y << "n"
            << "y' = " << y.derivatives()[0] << "n";
  return 0;
}
这个输出

x = 8

Y ' = 16

我建议将变量命名为x以外的东西,因为如果您希望对通常称为x的东西求导,那么它很容易混淆。因此,我们将其命名为a

  • 如果da/dx=0,则a为常数。显然,d/dx a²= 0。
  • 如果da/dx=1,那么本质上a=x。则d/dx a²= d/dx x²= 2x。