Skip to content

Commit

Permalink
fix float/rational vs mathconst comparisons
Browse files Browse the repository at this point in the history
  • Loading branch information
simonbyrne committed Dec 2, 2014
1 parent 892a1d3 commit b241c20
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
41 changes: 41 additions & 0 deletions base/constants.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,47 @@ end
=={s}(::MathConst{s}, ::MathConst{s}) = true
==(::MathConst, ::MathConst) = false

# MathConsts are irrational, so unequal to everything else
==(x::MathConst, y::Real) = false
==(x::Real, y::MathConst) = false

# MathConst vs FloatingPoint
<(x::MathConst, y::Float64) = Float64(x,RoundUp) <= y
<(x::Float64, y::MathConst) = x <= Float64(y,RoundDown)
<(x::MathConst, y::Float32) = Float32(x,RoundUp) <= y
<(x::Float32, y::MathConst) = x <= Float32(y,RoundDown)
<(x::MathConst, y::Float16) = Float32(x,RoundUp) <= y
<(x::Float16, y::MathConst) = x <= Float32(y,RoundDown)
<(x::MathConst, y::BigFloat) = with_bigfloat_precision(precision(y)+32) do
big(x) < y
end
<(x::BigFloat, y::MathConst) = with_bigfloat_precision(precision(x)+32) do
x < big(y)
end

<=(x::MathConst,y::FloatingPoint) = x < y
<=(x::FloatingPoint,y::MathConst) = x < y

# MathConst vs Rational
stagedfunction <{T}(x::MathConst, y::Rational{T})
bx = big(x())
bx < 0 && T <: Unsigned && return true
rx = rationalize(T,bx,tol=0)
rx < bx ? :($rx < y) : :($rx <= y)
end
stagedfunction <{T}(x::Rational{T}, y::MathConst)
by = big(y())
by < 0 && T <: Unsigned && return false
ry = rationalize(T,by,tol=0)
ry < by ? :(x <= $ry) : :(x < $ry)
end
<(x::MathConst, y::Rational{BigInt}) = big(x) < y
<(x::Rational{BigInt}, y::MathConst) = x < big(y)

<=(x::MathConst,y::Rational) = x < y
<=(x::Rational,y::MathConst) = x < y


hash(x::MathConst, h::UInt) = hash(object_id(x), h)

-(x::MathConst) = -float64(x)
Expand Down
23 changes: 23 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,29 @@ end
@test !(1//3 == NaN)
@test !(1//3 > NaN)

@test Float64(pi,RoundDown) < pi
@test Float64(pi,RoundUp) > pi
@test !(Float64(pi,RoundDown) > pi)
@test !(Float64(pi,RoundUp) < pi)
@test Float64(pi,RoundDown) <= pi
@test Float64(pi,RoundUp) >= pi
@test Float64(pi,RoundDown) != pi
@test Float64(pi,RoundUp) != pi

@test Float32(pi,RoundDown) < pi
@test Float32(pi,RoundUp) > pi
@test !(Float32(pi,RoundDown) > pi)
@test !(Float32(pi,RoundUp) < pi)

@test prevfloat(big(pi)) < pi
@test nextfloat(big(pi)) > pi
@test !(prevfloat(big(pi)) > pi)
@test !(nextfloat(big(pi)) < pi)

@test 2646693125139304345//842468587426513207 < pi
@test !(2646693125139304345//842468587426513207 > pi)
@test 2646693125139304345//842468587426513207 != pi

@test sqrt(2) == 1.4142135623730951

@test 1+1.5 == 2.5
Expand Down

0 comments on commit b241c20

Please sign in to comment.