Automatic Differentiation
 
Loading...
Searching...
No Matches
fabs.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_FUN_FABS_HPP
2#define STAN_MATH_REV_FUN_FABS_HPP
3
7
8namespace stan {
9namespace math {
10
50inline var fabs(const var& a) {
51 if (a.val() > 0.0) {
52 return a;
53 } else if (a.val() < 0.0) {
54 return -a;
55 } else if (a.val() == 0) {
56 return var(new vari(0));
57 } else {
59 [a](auto& vi) mutable { a.adj() = NOT_A_NUMBER; });
60 }
61}
62
70template <typename VarMat, require_var_matrix_t<VarMat>* = nullptr>
71inline auto fabs(const VarMat& a) {
72 return make_callback_var(
73 a.val().unaryExpr([](const auto x) {
74 if (unlikely(is_nan(x))) {
75 return NOT_A_NUMBER;
76 } else {
77 return std::abs(x);
78 }
79 }),
80 [a](const auto& vi) mutable {
81 for (Eigen::Index j = 0; j < vi.cols(); ++j) {
82 for (Eigen::Index i = 0; i < vi.rows(); ++i) {
83 const auto x = a.val().coeffRef(i, j);
84 if (unlikely(is_nan(x))) {
85 a.adj().coeffRef(i, j) = NOT_A_NUMBER;
86 } else if (x < 0.0) {
87 a.adj().coeffRef(i, j) -= vi.adj_.coeff(i, j);
88 } else {
89 a.adj().coeffRef(i, j) += vi.adj_.coeff(i, j);
90 }
91 }
92 }
93 });
94}
95
96} // namespace math
97} // namespace stan
98#endif
#define unlikely(x)
static constexpr double NOT_A_NUMBER
(Quiet) not-a-number value.
Definition constants.hpp:56
bool is_nan(T &&x)
Returns 1 if the input's value is NaN and 0 otherwise.
Definition is_nan.hpp:22
var_value< plain_type_t< T > > make_callback_var(T &&value, F &&functor)
Creates a new var initialized with a callback_vari with a given value and reverse-pass callback funct...
vari_value< double > vari
Definition vari.hpp:197
var_value< double > var
Definition var.hpp:1187
fvar< T > fabs(const fvar< T > &x)
Definition fabs.hpp:15
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...