Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions stan/math/fwd/fun/Phi_approx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#include <stan/math/fwd/meta.hpp>
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/fun/inv_logit.hpp>
#include <stan/math/fwd/fun/pow.hpp>
#include <stan/math/prim/fun/Phi_approx.hpp>
#include <cmath>

Expand All @@ -23,7 +22,8 @@ namespace math {
*/
template <typename T>
inline fvar<T> Phi_approx(const fvar<T>& x) {
return inv_logit(0.07056 * pow(x, 3.0) + 1.5976 * x);
const fvar<T> x_squared = x * x;
return inv_logit(0.07056 * x * x_squared + 1.5976 * x);
}

} // namespace math
Expand Down
3 changes: 2 additions & 1 deletion stan/math/opencl/kernels/device_functions/Phi_approx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ static constexpr const char* phi_approx_device_function
* @return Phi_approx(x)
*/
inline double Phi_approx(double x) {
return inv_logit(0.07056 * pow(x, 3.0) + 1.5976 * x);
const double x_squared = x * x;
return inv_logit(0.07056 * x * x_squared + 1.5976 * x);
}
// \cond
) "\n#endif\n"; // NOLINT
Expand Down
4 changes: 2 additions & 2 deletions stan/math/prim/fun/Phi_approx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ namespace math {
* @return Probability random sample is less than or equal to argument.
*/
inline double Phi_approx(double x) {
using std::pow;
return inv_logit(0.07056 * pow(x, 3.0) + 1.5976 * x);
const double x_squared = x * x;
return inv_logit(0.07056 * x * x_squared + 1.5976 * x);
}

/**
Expand Down
14 changes: 14 additions & 0 deletions test/unit/math/mix/fun/Phi_approx_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ TEST(mathMixMatFun, PhiApprox) {
stan::test::expect_unary_vectorized(f, -3.0, 1, 1.3, 3);
}

TEST(mathMixMatFun, PhiApprox_all_modes_give_the_same_value) {
using stan::math::fvar;
using stan::math::Phi_approx;
using stan::math::var;
for (int i = -2500; i <= 1000; ++i) {
const double x = 0.01 * i;
const double expected = Phi_approx(x);
EXPECT_EQ(expected, Phi_approx(var(x)).val()) << "x = " << x;
EXPECT_EQ(expected, Phi_approx(fvar<double>(x, 1)).val()) << "x = " << x;
EXPECT_EQ(expected, Phi_approx(fvar<var>(x, 1)).val().val()) << "x = " << x;
}
stan::math::recover_memory();
}

TEST(mathMixMatFun, PhiApprox_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
Expand Down
Loading