CoDiPack  2.2.0
A Code Differentiation Package
SciComp TU Kaiserslautern
Loading...
Searching...
No Matches
Example 6 - Forward mode tape evaluation

Goal: Evaluate a tape with forward AD mode.

Prerequisite: Tutorial 2 - Reverse mode AD

Function:

Real func(const Real& x) {
return x * x * x;
}
Represents a concrete lvalue in the CoDiPack expression tree.
Definition: activeType.hpp:52

Full code:

#include <codi.hpp>
#include <iostream>
using Tape = typename Real::Tape;
Real func(const Real& x) {
return x * x * x;
}
int main(int nargs, char** args) {
Real x = 4.0;
Tape& tape = Real::getTape();
// Step 1: Do a normal recording
tape.setActive();
tape.registerInput(x);
Real y = func(x);
tape.registerOutput(y);
tape.setPassive();
x.setGradient(1.0); // Step 2: Seed the input values
tape.evaluateForward(); // Step 3: Perform forward evaluation
// Step 4: Access gradients on the output values
std::cout << "f(4.0) = " << y << std::endl;
std::cout << "df/dx(4.0) = " << y.getGradient() << std::endl;
tape.reset();
return 0;
}
RealReverseGen< double > RealReverse
Definition: codi.hpp:120
static Tape & getTape()
Get a reference to the tape which manages this expression.
Definition: activeType.hpp:99
T_Tape Tape
See ActiveType.
Definition: activeType.hpp:55
void setGradient(Gradient const &g)
Set the gradient of this lvalue in the tape.
Definition: lhsExpressionInterface.hpp:120
Gradient getGradient() const
Get the gradient of this lvalue from the tape.
Definition: lhsExpressionInterface.hpp:115

Forward mode tape evaluation works the same as a reverse mode tape evaluation. Only the inputs need to be seeded and the derivatives are obtained from the outputs.