• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //           Copyright Matthew Pulver 2018 - 2019.
2 // Distributed under the Boost Software License, Version 1.0.
3 //      (See accompanying file LICENSE_1_0.txt or copy at
4 //           https://www.boost.org/LICENSE_1_0.txt)
5 
6 #include <boost/math/differentiation/autodiff.hpp>
7 #include <iostream>
8 
9 template <typename T>
fourth_power(T const & x)10 T fourth_power(T const& x) {
11   T x4 = x * x;  // retval in operator*() uses x4's memory via NRVO.
12   x4 *= x4;      // No copies of x4 are made within operator*=() even when squaring.
13   return x4;     // x4 uses y's memory in main() via NRVO.
14 }
15 
main()16 int main() {
17   using namespace boost::math::differentiation;
18 
19   constexpr unsigned Order = 5;                  // Highest order derivative to be calculated.
20   auto const x = make_fvar<double, Order>(2.0);  // Find derivatives at x=2.
21   auto const y = fourth_power(x);
22   for (unsigned i = 0; i <= Order; ++i)
23     std::cout << "y.derivative(" << i << ") = " << y.derivative(i) << std::endl;
24   return 0;
25 }
26 /*
27 Output:
28 y.derivative(0) = 16
29 y.derivative(1) = 32
30 y.derivative(2) = 48
31 y.derivative(3) = 48
32 y.derivative(4) = 24
33 y.derivative(5) = 0
34 **/
35