Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
AutoDiff examples

This page shows basic uses of the Auto Diff module.

Tracking first derivatives

AutoDiffScalar stores a scalar value together with its derivatives. The derivative vector size is the number of independent variables. A common pattern is to seed each independent variable with one unit vector:

Example:Output:
// SPDX-FileCopyrightText: The Eigen Authors
// SPDX-License-Identifier: MPL-2.0
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <contrib/Eigen/AutoDiff>
template <typename Scalar>
Scalar f(const Scalar& x, const Scalar& y) {
using std::sin;
return x * x * y + sin(y);
}
int main() {
ADScalar x(2.0, Eigen::Vector2d::UnitX());
ADScalar y(0.5, Eigen::Vector2d::UnitY());
ADScalar z = f(x, y);
std::cout << "f(x,y) = " << z.value() << "\n";
std::cout << "df/dx = " << z.derivatives()[0] << "\n";
std::cout << "df/dy = " << z.derivatives()[1] << "\n";
}
A scalar type replacement with automatic differentiation capability.
Definition AutoDiffScalar.h:100
f(x,y) = 2.47943
df/dx  = 2
df/dy  = 4.87758

Computing a Jacobian

AutoDiffJacobian wraps a functor whose operator() is templated on the scalar type. Calling it with a Jacobian pointer evaluates the functor with active AutoDiffScalar inputs and fills both the value and Jacobian:

Example:Output:
// SPDX-FileCopyrightText: The Eigen Authors
// SPDX-License-Identifier: MPL-2.0
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <contrib/Eigen/AutoDiff>
struct ExampleFunctor {
typedef Eigen::Vector2d InputType;
typedef Eigen::Vector2d ValueType;
template <typename Scalar>
void operator()(const Eigen::Matrix<Scalar, 2, 1>& x, Eigen::Matrix<Scalar, 2, 1>* y) const {
using std::sin;
(*y)[0] = x[0] * x[0] + x[1];
(*y)[1] = x[0] * sin(x[1]);
}
};
int main() {
Eigen::AutoDiffJacobian<ExampleFunctor> functor;
Eigen::AutoDiffJacobian<ExampleFunctor>::JacobianType jacobian;
x << 2.0, 0.5;
functor(x, &y, &jacobian);
std::cout << "value:\n" << y << "\n\n";
std::cout << "jacobian:\n" << jacobian << "\n";
}
Matrix< double, 2, 1 > Vector2d
value:
     4.5
0.958851

jacobian:
       4        1
0.479426  1.75517