Skip to content

Commit 7aafcdf

Browse files
authored
Merge pull request #3375 from Purna-Chandra-4706/fix-issue-3373-square
Efficiency: use multiplication over std::pow for squaring (#3373)
2 parents fe4800a + c98e30e commit 7aafcdf

2 files changed

Lines changed: 6 additions & 3 deletions

File tree

stan/math/prim/fun/square.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ namespace math {
2525
*/
2626
template <typename T, require_arithmetic_t<T>* = nullptr>
2727
inline double square(const T x) {
28-
return std::pow(x, 2);
28+
double x_dbl = x;
29+
return x_dbl * x_dbl;
2930
}
3031

3132
/**

stan/math/rev/fun/squared_distance.hpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ namespace math {
2121
inline var squared_distance(const var& a, const var& b) {
2222
check_finite("squared_distance", "a", a);
2323
check_finite("squared_distance", "b", b);
24-
return make_callback_vari(std::pow(a.val() - b.val(), 2),
24+
double difference = a.val() - b.val();
25+
return make_callback_vari(difference * difference,
2526
[a, b](const auto& vi) mutable {
2627
const double diff = 2.0 * (a.val() - b.val());
2728
a.adj() += vi.adj_ * diff;
@@ -35,7 +36,8 @@ inline var squared_distance(const var& a, const var& b) {
3536
inline var squared_distance(const var& a, double b) {
3637
check_finite("squared_distance", "a", a);
3738
check_finite("squared_distance", "b", b);
38-
return make_callback_vari(std::pow(a.val() - b, 2),
39+
double difference = a.val() - b;
40+
return make_callback_vari(difference * difference,
3941
[a, b](const auto& vi) mutable {
4042
a.adj() += vi.adj_ * 2.0 * (a.val() - b);
4143
});

0 commit comments

Comments
 (0)