user2658323 - 8 months ago 33
C++ Question

# How to retrive differentiation results with Eigen::AutoDiffScalar

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;
}
``````

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.

• If da/dx=0, then a is a constant. Then, obviously, d/dx a² = 0 as well.
• if da/dx=1, then essentially a=x. Then, d/dx a² = d/dx x² = 2x.