Reputation: 553
I am learning to use this library. Trying to differentitate a simple function, y = x^2
, does not yield the expected results (dy/dx = 2x = 16
when x = 8
).
#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;
}
Upvotes: 2
Views: 1511
Reputation: 5668
The scalar you have declared is literally just that – a scalar, so you are finding the derivative of a scalar (8*8), which is 0. To indicate that 8 is the value of the first variable, you need to set its first derivative to 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;
}
This outputs
x = 8
y = 64
y' = 16
I recommend naming the variable something other than x
, because it can be easily confusing if you're expecting to take the derivative with respect to something that is usually called x as well. So, let's call it a
instead.
Upvotes: 3