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
8
9namespace stan {
10namespace math {
11
51inline var fabs(const var& a) {
52 if (a.val() > 0.0) {
53 return a;
54 } else if (a.val() < 0.0) {
55 return -a;
56 } else if (a.val() == 0) {
57 return var(new vari(0));
58 } else {
60 [a](auto& vi) mutable { a.adj() = NOT_A_NUMBER; });
61 }
62}
63
71template <typename VarMat, require_var_matrix_t<VarMat>* = nullptr>
72inline auto fabs(const VarMat& a) {
73 return make_callback_var(
74 a.val().unaryExpr([](const auto x) {
75 if (unlikely(is_nan(x))) {
76 return NOT_A_NUMBER;
77 } else {
78 return std::abs(x);
79 }
80 }),
81 [a](const auto& vi) mutable {
82 for (Eigen::Index j = 0; j < vi.cols(); ++j) {
83 for (Eigen::Index i = 0; i < vi.rows(); ++i) {
84 const auto x = a.val().coeffRef(i, j);
85 if (unlikely(is_nan(x))) {
86 a.adj().coeffRef(i, j) = NOT_A_NUMBER;
87 } else if (x < 0.0) {
88 a.adj().coeffRef(i, j) -= vi.adj_.coeff(i, j);
89 } else {
90 a.adj().coeffRef(i, j) += vi.adj_.coeff(i, j);
91 }
92 }
93 }
94 });
95}
96
97} // namespace math
98} // namespace stan
99#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:16
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...