File: print_for.cpp

package info (click to toggle)
cppad 2025.00.00.2-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 11,552 kB
  • sloc: cpp: 112,594; sh: 5,972; ansic: 179; python: 71; sed: 12; makefile: 10
file content (81 lines) | stat: -rw-r--r-- 2,187 bytes parent folder | download | duplicates (2)
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
// 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 print_for_string.cpp}

Print During Zero Order Forward Mode: Example and Test
######################################################

{xrst_literal
   // BEGIN C++
   // END C++
}

{xrst_end print_for_string.cpp}
*/
// BEGIN C++
# include <cppad/cppad.hpp>

namespace {
   using std::endl;
   using CppAD::AD;

   // use of PrintFor to check for invalid function arguments
   AD<double> check_log(const AD<double>& u, std::ostream& s_out)
   {  // check AD<double> value during recording
      if( u <= 0 )
         s_out << "check_log: u = " << u << " which is <= 0\n";

      // check double value during zero order forward calculation
      PrintFor(u, "check_log: u = ", u , " which is <= 0\n");

      return log(u);
   }
}

bool print_for(void)
{  bool ok = true;
   using CppAD::PrintFor;
   std::stringstream stream_out;
   double eps99 = 99.0 * std::numeric_limits<double>::epsilon();

   // independent variable vector
   size_t np = 1;
   size_t nx = 1;
   size_t ny = 1;
   CPPAD_TESTVECTOR(AD<double>) ap(np), ax(nx), ay(ny);
   ap[0] = 1.0;
   ax[0] = 2.0;
   Independent(ax, ap);
   //
   // define f(x, p) = log(p) + log(x)
   ay[0] = check_log(ap[0], stream_out) + check_log(ax[0], stream_out);
   CppAD::ADFun<double> f(ax, ay);
   //
   // zero order forward
   // both x and p are positive so no output generated
   CPPAD_TESTVECTOR(double) p(np), x(nx), y(ny);
   p[0] = 1.0;
   x[0] = 2.0;
   f.new_dynamic(p);
   f.check_for_nan(false);
   y = f.Forward(0, x, stream_out);
   ok &= stream_out.str() == "";
   ok &= CppAD::NearEqual(y[0], std::log(p[0]) + std::log(x[0]), eps99, eps99);
   //
   // zero order forward
   // p is negative so output generated
   p[0] = -1.0;
   x[0] = 2.0;
   f.new_dynamic(p);
   f.check_for_nan(false);
   y = f.Forward(0, x, stream_out);
   ok &= stream_out.str() == "check_log: u = -1 which is <= 0\n";
   ok &= std::isnan(y[0]);
   //
   return ok;
}
// END C++