Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(stdlib)!: Add optimization for Number.pow(Rational, Int) #1716

Merged
merged 2 commits into from
Mar 5, 2023
Merged
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
5 changes: 5 additions & 0 deletions compiler/test/stdlib/number.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@ assert Number.pow(10223372036854775809, 10) ==
12472159440978016923768615307032788210916694000775261660538874886865415760948494778813645195039710006678013364969179502650466497057008288260604039903029954443675868581729857084924132550246401
assert Number.pow(1, 9223372036854775809) == 1
assert Number.pow(2.0, 9223372036854775809) == Infinity
assert Number.pow(1/2, 2) == 1/4
assert Number.pow(1/2, 3) == 1/8
assert Number.isRational(Number.pow(1/2, 2))
assert Number.isRational(Number.pow(1/2, 3))
assert Number.pow(1/2, -2) == 4
// exp
assert Number.exp(1) == 2.718281828459045
assert Number.exp(10) == 22026.465794806703
Expand Down
23 changes: 20 additions & 3 deletions stdlib/runtime/numbers.gr
Original file line number Diff line number Diff line change
Expand Up @@ -2804,13 +2804,30 @@ let rec expBySquaring = (y, x, n) => {
provide let (**) = (base, power) => {
let (==) = numberEq
let (!=) = (x, y) => !numberEq(x, y)
let basePtr = WasmI32.fromGrain(base)
let powerPtr = WasmI32.fromGrain(power)
if (base == 1 && power != 0) {
return 1
} else if (
isInteger(WasmI32.fromGrain(base)) && isInteger(WasmI32.fromGrain(power))
) {
} else if (isInteger(basePtr) && isInteger(powerPtr)) {
if (power < 0) return expBySquaring(1, 1 / base, power * -1)
else return expBySquaring(1, base, power)
} else if (isRational(basePtr) && isInteger(powerPtr)) {
// Apply expBySquaring to numerator and denominator
let numerator = WasmI32.fromGrain(base)
Memory.incRef(numerator)
let numerator = WasmI32.toGrain(numerator): Rational
let numerator = rationalNumerator(numerator)
let denominator = WasmI32.fromGrain(base)
Memory.incRef(denominator)
let denominator = WasmI32.toGrain(denominator): Rational
let denominator = rationalDenominator(denominator)
let numerator =
if (power < 0) expBySquaring(1, 1 / numerator, power * -1)
else expBySquaring(1, numerator, power)
let denominator =
if (power < 0) expBySquaring(1, 1 / denominator, power * -1)
else expBySquaring(1, denominator, power)
return numerator / denominator
} else {
// Based on https://git.musl-libc.org/cgit/musl/tree/src/math/pow.c
from WasmF64 use {
Expand Down