AutomaticDifferentiation/examples/firstAndSecondDerivative.cpp

67 lines
1.4 KiB
C++
Raw Normal View History

#include "../AutomaticDifferentiationVector.hpp"
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
#define PRINT_VAR(x) std::cout << #x << "\t= " << std::setprecision(16) << (x) << std::endl
#define PRINT_DUAL(x) std::cout << #x << "\t= " << std::fixed << std::setprecision(4) << std::setw(10) << (x).a << ", " << std::setw(10) << (x).b << std::endl
template<typename T>
T f(const T & x)
{
return 1 + x + x*x + 1/x + log(x);
}
template<typename T>
T df(const T & x)
{
return 2*x + 1 + 1.0/x - 1/pow(x, 2);
}
template<typename T>
T ddf(const T & x)
{
return 2 - 1/pow(x, 2) + 2/pow(x, 3);
}
int main()
{
double xdbl = 1.5;
{
cout << "Analytical\n";
cout << "f(x) = " << f(xdbl) << endl;
cout << "df(x)/dt = " << df(xdbl) << endl;
cout << "d²f(x)/dt = " << ddf(xdbl) << endl;
}
// 1st derivative forward
{
using Fd = DualVector<double,1>;
Fd x = xdbl;
x.diff(0);
Fd y = f(x);
cout << "\nForward\n";
cout << "f(x) = " << y.a << endl;
cout << "df(x)/dt = " << y.d(0) << endl;
}
// 2nd derivative forward
/*
{
using Fdd = DualVector<DualVector<double,2>,2>;
Fdd x(xdbl);
x.diff(0);
x.a.diff(1);
Fdd y = f(x);
cout << "\nForward 2nd der\n";
cout << "f(x) = " << y.a.a << endl;
cout << "df(x)/dt = " << y.d(0).a << endl;
cout << "d²f(x)/dt = " << y.d(0).d(1) << endl;
}//*/
return 0;
}