Skip to content

Commit

Permalink
Add ishalfodd function (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrodium authored Mar 11, 2024
1 parent d4dc006 commit 4e51170
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/HalfIntegers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export
# Functions
half,
ishalfinteger,
ishalfodd,
onehalf,
twice

Expand Down Expand Up @@ -561,6 +562,37 @@ ishalfinteger(::HalfIntegerOrInteger) = true
ishalfinteger(::AbstractIrrational) = false
ishalfinteger(::Missing) = missing

"""
ishalfodd(x)
Test whether `x` is numerically equal to some half-odd-integer.
# Examples
```jldoctest
julia> ishalfodd(3.5)
true
julia> ishalfodd(2)
false
julia> ishalfodd(1//3)
false
```
"""
ishalfodd(x::Number) = _isodd(twice(x))
ishalfodd(x::Rational) = denominator(x) == 2
ishalfodd(::Integer) = false
ishalfodd(::Missing) = missing

if VERSION v"1.7"
_isodd(x) = isodd(x)
else
_isodd(x::Real) = isodd(x)
_isodd(n::Number) = isreal(n) && _isodd(real(n))
_isodd(x::AbstractFloat) = isinteger(x) && abs(x) maxintfloat(x) && _isodd(Integer(x))
end

@static if VERSION v"1.7.0-DEV.263"
Base.range_start_stop_length(start::T, stop::T, len::Integer) where T<:HalfInteger =
Base._linspace(float(T), start, stop, len)
Expand Down
1 change: 1 addition & 0 deletions test/customtypes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Base.convert(::Type{One}, x::Int) = x == 1 ? One() : error("can't convert $x to
@testset "Properties" begin
@test isfinite(MyHalfInt(2))
@test ishalfinteger(MyHalfInt(3/2))
@test ishalfodd(MyHalfInt(3/2))
@test isinteger(MyHalfInt(3))
@test !isinteger(MyHalfInt(3/2))
@test iszero(MyHalfInt(0))
Expand Down
19 changes: 19 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,24 @@ end
@test !ishalfinteger(im)
end

@testset "ishalfodd" begin
for T in (halfinttypes..., halfuinttypes..., :BigHalfInt)
@eval @test !ishalfodd($T(3))
@eval @test ishalfodd($T(5/2))
end
@test !ishalfodd(5)
@test !ishalfodd(big(-5))
@test ishalfodd(5//2)
@test ishalfodd(-3//2)
@test !ishalfodd(4//3)
@test !ishalfodd(2.0)
@test ishalfodd(-7.5)
@test !ishalfodd(2.3)
@test !ishalfodd(π)
@test !ishalfodd(ℯ)
@test !ishalfodd(im)
end

@testset "isinteger" begin
for T in (halfinttypes..., :BigHalfInt)
@eval @test isinteger($T(3))
Expand Down Expand Up @@ -1690,6 +1708,7 @@ end
@test onehalf(missing) === onehalf(Missing) === missing

@test ishalfinteger(missing) === missing
@test ishalfodd(missing) === missing
end

include("ranges.jl")
Expand Down

0 comments on commit 4e51170

Please sign in to comment.