autodiff_multiprecision.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 <boost/multiprecision/cpp_bin_float.hpp>
  7. #include <iostream>
  8. using namespace boost::math::differentiation;
  9. template <typename W, typename X, typename Y, typename Z>
  10. promote<W, X, Y, Z> f(const W& w, const X& x, const Y& y, const Z& z) {
  11. using namespace std;
  12. return exp(w * sin(x * log(y) / z) + sqrt(w * z / (x * y))) + w * w / tan(z);
  13. }
  14. int main() {
  15. using float50 = boost::multiprecision::cpp_bin_float_50;
  16. constexpr unsigned Nw = 3; // Max order of derivative to calculate for w
  17. constexpr unsigned Nx = 2; // Max order of derivative to calculate for x
  18. constexpr unsigned Ny = 4; // Max order of derivative to calculate for y
  19. constexpr unsigned Nz = 3; // Max order of derivative to calculate for z
  20. // Declare 4 independent variables together into a std::tuple.
  21. auto const variables = make_ftuple<float50, Nw, Nx, Ny, Nz>(11, 12, 13, 14);
  22. auto const& w = std::get<0>(variables); // Up to Nw derivatives at w=11
  23. auto const& x = std::get<1>(variables); // Up to Nx derivatives at x=12
  24. auto const& y = std::get<2>(variables); // Up to Ny derivatives at y=13
  25. auto const& z = std::get<3>(variables); // Up to Nz derivatives at z=14
  26. auto const v = f(w, x, y, z);
  27. // Calculated from Mathematica symbolic differentiation.
  28. float50 const answer("1976.319600747797717779881875290418720908121189218755");
  29. std::cout << std::setprecision(std::numeric_limits<float50>::digits10)
  30. << "mathematica : " << answer << '\n'
  31. << "autodiff : " << v.derivative(Nw, Nx, Ny, Nz) << '\n'
  32. << std::setprecision(3)
  33. << "relative error: " << (v.derivative(Nw, Nx, Ny, Nz) / answer - 1) << '\n';
  34. return 0;
  35. }
  36. /*
  37. Output:
  38. mathematica : 1976.3196007477977177798818752904187209081211892188
  39. autodiff : 1976.3196007477977177798818752904187209081211892188
  40. relative error: 2.67e-50
  41. **/