1 #ifndef STAN_MATH_REV_FUN_INV_HPP
2 #define STAN_MATH_REV_FUN_INV_HPP
3 
4 #include <stan/math/rev/meta.hpp>
5 #include <stan/math/rev/core.hpp>
6 #include <stan/math/prim/fun/inv.hpp>
7 
8 namespace stan {
9 namespace math {
10 
11 /**
12  * @tparam T Arithmetic or a type inheriting from `EigenBase`.
13    \f[
14    \mbox{inv}(x) =
15    \begin{cases}
16      \frac{1}{x} & \mbox{if } -\infty\leq x \leq \infty \\[6pt]
17      \textrm{NaN} & \mbox{if } x = \textrm{NaN}
18    \end{cases}
19    \f]
20 
21    \f[
22    \frac{\partial\, \mbox{inv}(x)}{\partial x} =
23    \begin{cases}
24      -\frac{1}{x^2} & \mbox{if } -\infty\leq x\leq \infty \\[6pt]
25      \textrm{NaN} & \mbox{if } x = \textrm{NaN}
26    \end{cases}
27    \f]
28  *
29  */
30 template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inv(const var_value<T> & a)31 inline auto inv(const var_value<T>& a) {
32   auto denom = to_arena(as_array_or_scalar(square(a.val())));
33   return make_callback_var(inv(a.val()), [a, denom](auto& vi) mutable {
34     as_array_or_scalar(a.adj()) -= as_array_or_scalar(vi.adj()) / denom;
35   });
36 }
37 
38 }  // namespace math
39 }  // namespace stan
40 #endif
41