Skip to content

Commit bdd5b3e

Browse files
authored
Merge pull request #3207 from stan-dev/std_normal_log_qf-fwd-grad
Improve numerical stability of fwd gradients for std_normal_log_qf
2 parents 7108183 + 597fd7e commit bdd5b3e

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

stan/math/fwd/prob/std_normal_log_qf.hpp

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,7 @@ namespace math {
1616
template <typename T>
1717
inline fvar<T> std_normal_log_qf(const fvar<T>& p) {
1818
const T xv = std_normal_log_qf(p.val_);
19-
int p_sign = 1;
20-
auto p_d = p.d_;
21-
if (p.d_ < 0) {
22-
p_sign = -1;
23-
p_d *= -1;
24-
}
25-
return fvar<T>(
26-
xv,
27-
p_sign * exp(p.val_ + log(p_d) - NEG_LOG_SQRT_TWO_PI + 0.5 * square(xv)));
19+
return fvar<T>(xv, p.d_ * exp(p.val_ - std_normal_lpdf(xv)));
2820
}
2921
} // namespace math
3022
} // namespace stan

test/unit/math/mix/prob/std_normal_log_qf_test.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,14 @@ TEST_F(AgradRev, mathMixMatFunLog_stdNormalLogQfVarmat) {
4646
}
4747
expect_ad_vector_matvar(f, A);
4848
}
49+
50+
TEST_F(AgradRev, GradientStabilityStdNormalLogQf) {
51+
auto f = [](const auto& y) {
52+
return stan::math::sum(stan::math::std_normal_log_qf(y));
53+
};
54+
55+
Eigen::VectorXd y1(2);
56+
y1 << -10, -2;
57+
58+
stan::test::expect_ad(f, y1);
59+
}

0 commit comments

Comments
 (0)