Stan Math Library  2.20.0
reverse mode automatic differentiation
operator_subtraction.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_REV_CORE_OPERATOR_SUBTRACTION_HPP
2 #define STAN_MATH_REV_CORE_OPERATOR_SUBTRACTION_HPP
3 
9 #include <limits>
10 
11 namespace stan {
12 namespace math {
13 
14 namespace internal {
15 class subtract_vv_vari : public op_vv_vari {
16  public:
18  : op_vv_vari(avi->val_ - bvi->val_, avi, bvi) {}
19  void chain() {
20  if (unlikely(is_any_nan(avi_->val_, bvi_->val_))) {
21  avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
22  bvi_->adj_ = std::numeric_limits<double>::quiet_NaN();
23  } else {
24  avi_->adj_ += adj_;
25  bvi_->adj_ -= adj_;
26  }
27  }
28 };
29 
30 class subtract_vd_vari : public op_vd_vari {
31  public:
32  subtract_vd_vari(vari* avi, double b) : op_vd_vari(avi->val_ - b, avi, b) {}
33  void chain() {
34  if (unlikely(is_any_nan(avi_->val_, bd_)))
35  avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
36  else
37  avi_->adj_ += adj_;
38  }
39 };
40 
41 class subtract_dv_vari : public op_dv_vari {
42  public:
43  subtract_dv_vari(double a, vari* bvi) : op_dv_vari(a - bvi->val_, a, bvi) {}
44  void chain() {
45  if (unlikely(is_any_nan(ad_, bvi_->val_)))
46  bvi_->adj_ = std::numeric_limits<double>::quiet_NaN();
47  else
48  bvi_->adj_ -= adj_;
49  }
50 };
51 } // namespace internal
52 
91 inline var operator-(const var& a, const var& b) {
92  return var(new internal::subtract_vv_vari(a.vi_, b.vi_));
93 }
94 
106 inline var operator-(const var& a, double b) {
107  if (b == 0.0)
108  return a;
109  return var(new internal::subtract_vd_vari(a.vi_, b));
110 }
111 
123 inline var operator-(double a, const var& b) {
124  return var(new internal::subtract_dv_vari(a, b.vi_));
125 }
126 
127 } // namespace math
128 } // namespace stan
129 #endif
fvar< T > operator-(const fvar< T > &x1, const fvar< T > &x2)
Return the difference of the specified arguments.
The variable implementation base class.
Definition: vari.hpp:30
bool is_any_nan(const T &x)
Returns true if the input is NaN and false otherwise.
Definition: is_any_nan.hpp:21
void chain()
Apply the chain rule to this variable based on the variables on which it depends. ...
Independent (input) and dependent (output) variables for gradients.
Definition: var.hpp:33
friend class var
Definition: vari.hpp:32
const double val_
The value of this variable.
Definition: vari.hpp:38
#define unlikely(x)
Definition: likely.hpp:9
vari * vi_
Pointer to the implementation of this variable.
Definition: var.hpp:45
void chain()
Apply the chain rule to this variable based on the variables on which it depends. ...
double adj_
The adjoint of this variable, which is the partial derivative of this variable with respect to the ro...
Definition: vari.hpp:44
void chain()
Apply the chain rule to this variable based on the variables on which it depends. ...

     [ Stan Home Page ] © 2011–2018, Stan Development Team.