Skip to content

Commit

Permalink
added rand for TypedEndpointsInterval (#116)
Browse files Browse the repository at this point in the history
* added rand for TypedEndpointsInterval

* disallow rand(::TypedInterval{:closed, :open})
  • Loading branch information
zsunberg authored Sep 10, 2022
1 parent 3054532 commit 41028c0
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/interval.jl
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,11 @@ end

# random sampling from interval
Random.gentype(::Type{Interval{L,R,T}}) where {L,R,T} = float(T)
function Random.rand(rng::AbstractRNG, i::Random.SamplerTrivial{ClosedInterval{T}}) where {T<:Real}
function Random.rand(rng::AbstractRNG, i::Random.SamplerTrivial{<:TypedEndpointsInterval{:closed, :closed, T}}) where T<:Real
_i = i[]
isempty(_i) && throw(ArgumentError("The interval should be non-empty."))
a,b = endpoints(_i)
t = rand(rng, float(T))
t = rand(rng, float(T)) # technically this samples from [0, 1), but we still allow it with TypedEndpointsInterval{:closed, :closed} for convenience
return clamp(t*a+(1-t)*b, _i)
end

Expand Down
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,11 @@ struct IncompleteInterval <: AbstractInterval{Int} end
rand(i4,10) i4
rand(i5,10) i5
end

# special test to catch issue mentioned at the end of https://github.com/JuliaApproximation/DomainSets.jl/pull/112
struct RandTestUnitInterval <: TypedEndpointsInterval{:closed, :closed, Float64} end
IntervalSets.endpoints(::RandTestUnitInterval) = (-1.0, 1.0)
@test rand(RandTestUnitInterval()) in -1.0..1.0
end

@testset "IteratorSize" begin
Expand Down

0 comments on commit 41028c0

Please sign in to comment.