如何用Eigen::AutoDiffScalar检索微分结果
How to retrive differentiation results with Eigen::AutoDiffScalar
我正在学习使用这个库。试图微分一个简单的函数,y = x^2
,不会得到预期的结果(x = 8
时dy/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。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用VerQueryValue检索应用程序的文件描述
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 永远不要从 std::p ackaged_task 中检索 std::future 的结果是否安全?
- 如何从谷神星求解器结果中检索异常值
- 在MFC中检索键盘中断结果
- 使用 search-ms: 或 search: 协议将搜索结果作为 IShellItem 进行检索
- 无法检索正则表达式匹配结果 - MFC / C++
- GLSL -从阴影立方体图中检索值时结果不正确
- 如何用Eigen::AutoDiffScalar检索微分结果
- 如何检索netstat命令的结果
- 检索用户选择的结果作为调用Qt中外部程序的输入