Skip to content

Commit

Permalink
make ^ and .^ types consistent (part of #3274)
Browse files Browse the repository at this point in the history
For example, before this patch:

    julia> typeof(int32(2) ^ int64(3))
    Int32

    julia> eltype([int32(2)] .^ [int64(3)])
    Int64  # Int32 after this patch

    julia> typeof(complex(2) ^ complex(3))
    Complex{Float64}

    julia> eltype([complex(2)] .^ [complex(3)])
    Complex{Int}  # Complex{Float64} after this patch
  • Loading branch information
nolta committed Jul 7, 2015
1 parent 4c2dfea commit f8eafc2
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
5 changes: 3 additions & 2 deletions base/broadcast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,9 @@ function .//(A::AbstractArray, B::AbstractArray)
broadcast!(//, Array(type_rdiv(eltype(A), eltype(B)), broadcast_shape(A, B)), A, B)
end

type_pow(T,S) = promote_type(T,S)
type_pow{S<:Integer}(::Type{Bool},::Type{S}) = Bool
@generated function type_pow(T,S)
:(promote_type(Base.return_types(^,(T,S))...))
end
type_pow{S}(T,::Type{Rational{S}}) = type_pow(T, type_div(S, S))

function .^(A::AbstractArray, B::AbstractArray)
Expand Down
8 changes: 3 additions & 5 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -385,13 +385,15 @@ function isqrt(x::BigInt)
return z
end

^(x::BigInt, y::Bool) = y ? x : one(x)

function ^(x::BigInt, y::Culong)
z = BigInt()
ccall((:__gmpz_pow_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, y)
return z
end

function bigint_pow(x::BigInt, y::Integer)
function ^(x::BigInt, y::Integer)
if y<0; throw(DomainError()); end
if x== 1; return x; end
if x==-1; return isodd(y) ? x : -x; end
Expand All @@ -411,10 +413,6 @@ function bigint_pow(x::BigInt, y::Integer)
return x^convert(Culong, y)
end

^(x::BigInt , y::BigInt ) = bigint_pow(x, y)
^(x::BigInt , y::Bool ) = y ? x : one(x)
^(x::BigInt , y::Integer) = bigint_pow(x, y)

function powermod(x::BigInt, p::BigInt, m::BigInt)
p < 0 && throw(DomainError())
r = BigInt()
Expand Down
13 changes: 13 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2504,3 +2504,16 @@ end

# fix 0x2^big(9) = big(512), while 0x2^9 = 0x0
@test 0x2^9 === 0x2^big(9) === 0x0

# issue #3274
let
realtypes = [Int8, Int16, Int32, Int64, Int128,
UInt8, UInt16, UInt32, UInt64, UInt128,
Float32, Float64, BigInt, BigFloat]
alltypes = [realtypes; [Complex{T} for T in realtypes]]

for T in alltypes, S in alltypes
a,b = T(2),S(3)
@test typeof(a^b) === eltype([a].^[b])
end
end

0 comments on commit f8eafc2

Please sign in to comment.