Skip to content

Commit

Permalink
Fix big(1)^big(-1) (#50821)
Browse files Browse the repository at this point in the history
This PR gives BigInt exponentiation the same edge-case behavior as other
integer exponentiation.

The normal integer exponentiation checks if `x` is `1` or `-1` before
erroring if the power is negative.

https://github.com/JuliaLang/julia/blob/9f9e989f241fad1ae03c3920c20a93d8017a5b8f/base/intfuncs.jl#L283-L287

With this PR `big(1)^big(-1) == 1`, `big(-1)^big(-1) == -1` and
`big(-1)^big(-2) == 1`

---------

Co-authored-by: Sukera <11753998+Seelengrab@users.noreply.github.com>
  • Loading branch information
nhz2 and Seelengrab authored Aug 11, 2023
1 parent eb4416b commit 3838dab
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
4 changes: 2 additions & 2 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -628,11 +628,11 @@ isqrt(x::BigInt) = MPZ.sqrt(x)
^(x::BigInt, y::Culong) = MPZ.pow_ui(x, y)

function bigint_pow(x::BigInt, y::Integer)
x == 1 && return x
x == -1 && return isodd(y) ? x : -x
if y<0; throw(DomainError(y, "`y` cannot be negative.")); end
@noinline throw1(y) =
throw(OverflowError("exponent $y is too large and computation will overflow"))
if x== 1; return x; end
if x==-1; return isodd(y) ? x : -x; end
if y>typemax(Culong)
x==0 && return x

Expand Down
21 changes: 19 additions & 2 deletions test/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,25 @@ end
@test isqrt(big(4)) == 2
@test isqrt(big(5)) == 2

@test big(5)^true == big(5)
@test big(5)^false == one(BigInt)

@testset "Exponentiation operator" begin
@test big(5)^true == big(5)
@test big(5)^false == one(BigInt)
testvals = Int8[-128:-126; -3:3; 125:127]
@testset "BigInt and Int8 are consistent: $i^$j" for i in testvals, j in testvals
int8_res = try
i^j
catch e
e
end
if int8_res isa Int8
@test (big(i)^big(j)) % Int8 === int8_res
else
# Test both have exception of the same type
@test_throws typeof(int8_res) big(i)^big(j)
end
end
end

@testset "math ops returning BigFloat" begin
# operations that when applied to Int64 give Float64, should give BigFloat
Expand Down

0 comments on commit 3838dab

Please sign in to comment.