66 lines
1.3 KiB
C++
Executable file
66 lines
1.3 KiB
C++
Executable file
#include "../AutomaticDifferentiation.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 = Dual<double>;
|
|
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 = Dual<Dual<double>>;
|
|
Fdd x(xdbl);
|
|
x.diff(0,2);
|
|
x.x().diff(1,2);
|
|
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;
|
|
}
|