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

make cmp with BigInt return in [-1, 0, 1] #28780

Merged
merged 2 commits into from
Aug 23, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 4 additions & 4 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -487,13 +487,13 @@ count_ones_abs(x::BigInt) = iszero(x) ? 0 : MPZ.mpn_popcount(x)

divrem(x::BigInt, y::BigInt) = MPZ.tdiv_qr(x, y)

cmp(x::BigInt, y::BigInt) = MPZ.cmp(x, y)
cmp(x::BigInt, y::ClongMax) = MPZ.cmp_si(x, y)
cmp(x::BigInt, y::CulongMax) = MPZ.cmp_ui(x, y)
cmp(x::BigInt, y::BigInt) = sign(MPZ.cmp(x, y))
cmp(x::BigInt, y::ClongMax) = sign(MPZ.cmp_si(x, y))
cmp(x::BigInt, y::CulongMax) = sign(MPZ.cmp_ui(x, y))
cmp(x::BigInt, y::Integer) = cmp(x, big(y))
cmp(x::Integer, y::BigInt) = -cmp(y, x)

cmp(x::BigInt, y::CdoubleMax) = isnan(y) ? -1 : MPZ.cmp_d(x, y)
cmp(x::BigInt, y::CdoubleMax) = isnan(y) ? -1 : sign(MPZ.cmp_d(x, y))
cmp(x::CdoubleMax, y::BigInt) = -cmp(y, x)

isqrt(x::BigInt) = MPZ.sqrt(x)
Expand Down
13 changes: 13 additions & 0 deletions test/bigint.jl
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,16 @@ end

# Issue #24298
@test mod(BigInt(6), UInt(5)) == mod(6, 5)

@testset "cmp has values in [-1, 0, 1], issue #28780" begin
bigrand() = rand(-big(2)^rand(1:rand(1:1000)):big(2)^rand(1:rand(1:1000)))
for T in (Base.BitInteger_types..., BigInt, Float64, Float32, Float16, BigFloat)
@test cmp(big(2)^130, one(T)) == 1
@test cmp(-big(2)^130, one(T)) == -1
Copy link
Member

@StefanKarpinski StefanKarpinski Aug 20, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about testing these with === to ensure that the type matches as well? And throw in some tests where the result is 0 as well...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, done. I removed the testing with BigFloat as this is handled in the MPFR module, and can return Int32. I can make a PR for MPFR if you think it's useful.

T === BigInt && continue
@test cmp(big(2)^130, rand(T)) == 1
@test cmp(-big(2)^130, rand(T)) == -1
@test cmp(bigrand(), rand(T)) ∈ (-1, 0, 1)
end
@test cmp(bigrand(), bigrand()) ∈ (-1, 0, 1)
end