Skip to content

Commit

Permalink
don't throw DomainError for negative integer powers of ±1 (JuliaLang#…
Browse files Browse the repository at this point in the history
…18342)

* don't throw DomainError for negative integer powers of ±1

* fix replutil test that was expecting 1^(-1) to fail
  • Loading branch information
stevengj authored and mfasi committed Sep 5, 2016
1 parent 3befe84 commit 617b2a6
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
4 changes: 3 additions & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ function power_by_squaring(x_, p::Integer)
elseif p == 2
return x*x
elseif p < 0
x == 1 && return copy(x)
x == -1 && return iseven(p) ? one(x) : copy(x)
throw(DomainError())
end
t = trailing_zeros(p) + 1
Expand All @@ -185,7 +187,7 @@ function power_by_squaring(x_, p::Integer)
end
power_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x)
function power_by_squaring(x::Bool, p::Integer)
p < 0 && throw(DomainError())
p < 0 && !x && throw(DomainError())
return (p==0) | x
end

Expand Down
4 changes: 4 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,10 @@ end
@test_throws DomainError 2 ^ -2
@test_throws DomainError (-2)^(2.2)
@test_throws DomainError (-2.0)^(2.2)
@test_throws DomainError false ^ -2
@test 1 ^ -2 === (-1) ^ -2 === 1
@test (-1) ^ -3 === -1
@test true ^ -2 === true

# issue #13748
let A = [1 2; 3 4]; B = [5 6; 7 8]; C = [9 10; 11 12]
Expand Down
2 changes: 1 addition & 1 deletion test/replutil.jl
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ immutable TypeWithIntParam{T <: Integer} end
let undefvar
err_str = @except_strbt sqrt(-1) DomainError
@test contains(err_str, "Try sqrt(complex(x)).")
err_str = @except_strbt 1^(-1) DomainError
err_str = @except_strbt 2^(-1) DomainError
@test contains(err_str, "Cannot raise an integer x to a negative power -n")
err_str = @except_strbt (-1)^0.25 DomainError
@test contains(err_str, "Exponentiation yielding a complex result requires a complex argument")
Expand Down

0 comments on commit 617b2a6

Please sign in to comment.