autodiff_fourth_power.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  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. #include <boost/math/differentiation/autodiff.hpp>
  6. #include <iostream>
  7. template <typename T>
  8. T fourth_power(T const& x) {
  9. T x4 = x * x; // retval in operator*() uses x4's memory via NRVO.
  10. x4 *= x4; // No copies of x4 are made within operator*=() even when squaring.
  11. return x4; // x4 uses y's memory in main() via NRVO.
  12. }
  13. int main() {
  14. using namespace boost::math::differentiation;
  15. constexpr unsigned Order = 5; // Highest order derivative to be calculated.
  16. auto const x = make_fvar<double, Order>(2.0); // Find derivatives at x=2.
  17. auto const y = fourth_power(x);
  18. for (unsigned i = 0; i <= Order; ++i)
  19. std::cout << "y.derivative(" << i << ") = " << y.derivative(i) << std::endl;
  20. return 0;
  21. }
  22. /*
  23. Output:
  24. y.derivative(0) = 16
  25. y.derivative(1) = 32
  26. y.derivative(2) = 48
  27. y.derivative(3) = 48
  28. y.derivative(4) = 24
  29. y.derivative(5) = 0
  30. **/