Skip to content

Commit

Permalink
replace pxt_powi implementation with better one (#1484)
Browse files Browse the repository at this point in the history
* replace pxt_powi implementation with better one

* add comment
  • Loading branch information
riknoll authored Aug 26, 2024
1 parent 2580378 commit 151e6f7
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions libs/base/core.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1338,8 +1338,27 @@ namespace Math_ {
//%
TNumber pow(TNumber x, TNumber y) {
#ifdef PXT_POWI
// regular pow() from math.h is 4k of code
return fromDouble(__builtin_powi(toDouble(x), toInt(y)));
// regular pow() from math.h is 4k of code, but it can
// also be expressed as exp(y * log(x)) which is less
// performant than pow() but doesn't increase code size
double dx = toDouble(x);
double dy = toDouble(y);

// shortcut to integer pow if y is an integer
if (::floor(dy) == dy) {
return fromDouble(__builtin_powi(dx, dy));
}
if (dx > 0) {
return fromDouble(::exp(dy * ::log(dx)));
}
if (dx == 0) {
if (dy < 0) {
// positive infinity
return fromDouble(HUGE_VAL);
}
return x;
}
return fromDouble(::log(dx));
#else
return fromDouble(::pow(toDouble(x), toDouble(y)));
#endif
Expand Down

0 comments on commit 151e6f7

Please sign in to comment.