Skip to content

Commit 617b2a6

Browse files
stevengjmfasi
authored andcommitted
don't throw DomainError for negative integer powers of ±1 (#18342)
* don't throw DomainError for negative integer powers of ±1 * fix replutil test that was expecting 1^(-1) to fail
1 parent 3befe84 commit 617b2a6

File tree

3 files changed

+8
-2
lines changed

3 files changed

+8
-2
lines changed

base/intfuncs.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ function power_by_squaring(x_, p::Integer)
165165
elseif p == 2
166166
return x*x
167167
elseif p < 0
168+
x == 1 && return copy(x)
169+
x == -1 && return iseven(p) ? one(x) : copy(x)
168170
throw(DomainError())
169171
end
170172
t = trailing_zeros(p) + 1
@@ -185,7 +187,7 @@ function power_by_squaring(x_, p::Integer)
185187
end
186188
power_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x)
187189
function power_by_squaring(x::Bool, p::Integer)
188-
p < 0 && throw(DomainError())
190+
p < 0 && !x && throw(DomainError())
189191
return (p==0) | x
190192
end
191193

test/math.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,10 @@ end
827827
@test_throws DomainError 2 ^ -2
828828
@test_throws DomainError (-2)^(2.2)
829829
@test_throws DomainError (-2.0)^(2.2)
830+
@test_throws DomainError false ^ -2
831+
@test 1 ^ -2 === (-1) ^ -2 === 1
832+
@test (-1) ^ -3 === -1
833+
@test true ^ -2 === true
830834

831835
# issue #13748
832836
let A = [1 2; 3 4]; B = [5 6; 7 8]; C = [9 10; 11 12]

test/replutil.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ immutable TypeWithIntParam{T <: Integer} end
257257
let undefvar
258258
err_str = @except_strbt sqrt(-1) DomainError
259259
@test contains(err_str, "Try sqrt(complex(x)).")
260-
err_str = @except_strbt 1^(-1) DomainError
260+
err_str = @except_strbt 2^(-1) DomainError
261261
@test contains(err_str, "Cannot raise an integer x to a negative power -n")
262262
err_str = @except_strbt (-1)^0.25 DomainError
263263
@test contains(err_str, "Exponentiation yielding a complex result requires a complex argument")

0 commit comments

Comments
 (0)