Skip to content

Commit ab4849d

Browse files
authored
Merge pull request #3229 from stan-dev/fix/apply-scalar-bad-size-after-move
apply_scalar_binary: avoid using moved-from variable for result size.
2 parents f98e093 + c877ef9 commit ab4849d

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

stan/math/prim/functor/apply_scalar_binary.hpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ template <typename F, typename T1, typename T2,
306306
inline auto apply_scalar_binary(F&& f, T1&& x, T2&& y) {
307307
decltype(auto) x_vec = as_column_vector_or_scalar(std::forward<T1>(x));
308308
using T_return = std::decay_t<decltype(f(x[0], y))>;
309-
std::vector<T_return> result(x.size());
309+
std::vector<T_return> result(x_vec.size());
310310
Eigen::Map<Eigen::Matrix<T_return, -1, 1>>(result.data(), result.size())
311311
= x_vec.unaryExpr(
312312
[f_ = std::forward<F>(f), y](auto&& v) { return f_(v, y); });
@@ -335,9 +335,9 @@ template <typename F, typename T1, typename T2,
335335
require_stan_scalar_t<T1>* = nullptr,
336336
require_std_vector_vt<is_stan_scalar, T2>* = nullptr>
337337
inline auto apply_scalar_binary(F&& f, T1&& x, T2&& y) {
338-
decltype(auto) y_vec = as_column_vector_or_scalar(y);
339338
using T_return = std::decay_t<decltype(f(x, y[0]))>;
340-
std::vector<T_return> result(y.size());
339+
decltype(auto) y_vec = as_column_vector_or_scalar(std::forward<T2>(y));
340+
std::vector<T_return> result(y_vec.size());
341341
Eigen::Map<Eigen::Matrix<T_return, -1, 1>>(result.data(), result.size())
342342
= y_vec.unaryExpr(
343343
[f_ = std::forward<F>(f), x](auto&& v) { return f_(x, v); });

test/unit/math/prim/fun/log_modified_bessel_first_kind_test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,22 @@ TEST(MathFunctions, log_modified_bessel_first_kind_vec) {
9191
in2 << 7.3, 0.7, 2.8;
9292
stan::test::binary_scalar_tester(f, in1, in2);
9393
}
94+
95+
TEST(MathFunctions, log_modified_bessel_first_kind_aki_regression) {
96+
// https://github.com/stan-dev/cmdstan/issues/1324#issuecomment-3206462728
97+
98+
using stan::math::log_modified_bessel_first_kind;
99+
double rho = 0.5;
100+
double alpha = 2.0;
101+
int M = 20;
102+
103+
double a = (1 / stan::math::pow(rho, 2));
104+
Eigen::Matrix<double, -1, 1> q = stan::math::exp(stan::math::add(
105+
stan::math::log(alpha),
106+
stan::math::multiply(
107+
0.5,
108+
stan::math::add(
109+
(stan::math::log(2) - a),
110+
stan::math::to_vector(stan::math::log_modified_bessel_first_kind(
111+
stan::math::linspaced_int_array(M, 1, M), a))))));
112+
}

0 commit comments

Comments
 (0)