1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
// SPDX-FileCopyrightText: Bradley M. Bell <bradbell@seanet.com>
// SPDX-FileContributor: 2003-22 Bradley M. Bell
// ----------------------------------------------------------------------------
/*
{xrst_begin pow.cpp}
The AD Power Function: Example and Test
#######################################
{xrst_literal
// BEGIN C++
// END C++
}
{xrst_end pow.cpp}
*/
// BEGIN C++
# include <cppad/cppad.hpp>
# include <cmath>
bool pow(void)
{ bool ok = true;
using CppAD::AD;
using CppAD::NearEqual;
double eps = 10. * std::numeric_limits<double>::epsilon();
// domain space vector
size_t n = 2;
double x = 0.5;
double y = 2.;
CPPAD_TESTVECTOR(AD<double>) axy(n);
axy[0] = x;
axy[1] = y;
// declare independent variables and start tape recording
CppAD::Independent(axy);
// range space vector
size_t m = 3;
CPPAD_TESTVECTOR(AD<double>) az(m);
az[0] = CppAD::pow(axy[0], axy[1]); // pow(variable, variable)
az[1] = CppAD::pow(axy[0], y); // pow(variable, parameter)
az[2] = CppAD::pow(x, axy[1]); // pow(parameter, variable)
// create f: axy -> az and stop tape recording
CppAD::ADFun<double> f(axy, az);
// check value
double check = std::pow(x, y);
size_t i;
for(i = 0; i < m; i++)
ok &= NearEqual(az[i] , check, eps, eps);
// forward computation of first partial w.r.t. x
CPPAD_TESTVECTOR(double) dxy(n);
CPPAD_TESTVECTOR(double) dz(m);
dxy[0] = 1.;
dxy[1] = 0.;
dz = f.Forward(1, dxy);
check = y * std::pow(x, y-1.);
ok &= NearEqual(dz[0], check, eps, eps);
ok &= NearEqual(dz[1], check, eps, eps);
ok &= NearEqual(dz[2], 0., eps, eps);
// forward computation of first partial w.r.t. y
dxy[0] = 0.;
dxy[1] = 1.;
dz = f.Forward(1, dxy);
check = std::log(x) * std::pow(x, y);
ok &= NearEqual(dz[0], check, eps, eps);
ok &= NearEqual(dz[1], 0., eps, eps);
ok &= NearEqual(dz[2], check, eps, eps);
// reverse computation of derivative of z[0] + z[1] + z[2]
CPPAD_TESTVECTOR(double) w(m);
CPPAD_TESTVECTOR(double) dw(n);
w[0] = 1.;
w[1] = 1.;
w[2] = 1.;
dw = f.Reverse(1, w);
check = y * std::pow(x, y-1.);
ok &= NearEqual(dw[0], 2. * check, eps, eps);
check = std::log(x) * std::pow(x, y);
ok &= NearEqual(dw[1], 2. * check, eps, eps);
// use a VecAD<Base>::reference object with pow
CppAD::VecAD<double> v(2);
AD<double> zero(0);
AD<double> one(1);
v[zero] = axy[0];
v[one] = axy[1];
AD<double> result = CppAD::pow(v[zero], v[one]);
ok &= NearEqual(result, az[0], eps, eps);
return ok;
}
// END C++
|