Sacado Package Browser (Single Doxygen Collection)  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sparse_example.cpp
Go to the documentation of this file.
1 // @HEADER
2 // *****************************************************************************
3 // Sacado Package
4 //
5 // Copyright 2006 NTESS and the Sacado contributors.
6 // SPDX-License-Identifier: LGPL-2.1-or-later
7 // *****************************************************************************
8 // @HEADER
9 
10 // dfad_example
11 //
12 // usage:
13 // dfad_example
14 //
15 // output:
16 // prints the results of differentiating a simple function with forward
17 // mode AD using the Sacado::Fad::DFad class (uses dynamic memory
18 // allocation for number of derivative components).
19 
20 #include <iostream>
21 #include <iomanip>
22 
23 #include "Sacado_No_Kokkos.hpp"
24 
25 // The function to differentiate
26 template <typename ScalarT>
27 ScalarT func(const ScalarT& a, const ScalarT& b, const ScalarT& c) {
28  ScalarT r = std::log(b+1.)/std::sin(a);
29 
30  return r;
31 }
32 
34 
35 int main(int argc, char **argv)
36 {
37  double pi = std::atan(1.0)*4.0;
38 
39  // Values of function arguments
40  double a = pi/4;
41  double b = 2.0;
42  double c = 3.0;
43 
44  // Number of independent variables
45  int num_deriv = 3;
46 
47  // Fad objects
48  FadType afad(num_deriv, 0, a); // First (0) indep. var
49  FadType bfad(num_deriv, 1, b); // Second (1) indep. var
50  FadType cfad(num_deriv, 2, c); // Third (2) indep. var
51  FadType rfad; // Result
52 
53  // Compute function
54  double r = func(a, b, c);
55 
56  // Compute function and derivative with AD
57  rfad = func(afad, bfad, cfad);
58 
59  std::cout << rfad << std::endl;
60 
61  // Extract value and derivatives
62  double r_ad = rfad.val(); // r
63  bool drda_ad = rfad.dx(0); // dr/da
64  bool drdb_ad = rfad.dx(1); // dr/db
65  bool drdc_ad = rfad.dx(2); // dr/dc
66 
67  double tol = 1.0e-14;
68  if (std::fabs(r - r_ad) < tol && drda_ad && drdb_ad && !drdc_ad) {
69  std::cout << "\nExample passed!" << std::endl;
70  return 0;
71  }
72  else {
73  std::cout <<"\nSomething is wrong, example failed!" << std::endl;
74  return 1;
75  }
76 }
Sacado::Fad::DFad< double > FadType
atan(expr.val())
expr expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c *expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 c
int main()
Definition: ad_example.cpp:171
sin(expr.val())
log(expr.val())
const double tol
const T func(int n, T *x)
Definition: ad_example.cpp:29
fabs(expr.val())