Skip to content

Commit d54ee11

Browse files
authored
Add support for rand(1..2) (#104)
* add dependency on Random * add dependency on Random * add draft method for rand(::Interval) * update Random.rand and Random.gentype * add clamp and replace Interval{L,R} with ClosedInterval in Random.rand * add tests for rand
1 parent 42f7855 commit d54ee11

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

Project.toml

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = "0.7.0"
44

55
[deps]
66
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
7+
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
78
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
89

910
[compat]

src/IntervalSets.jl

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import Base: eltype, convert, show, in, length, isempty, isequal, issubset, ==,
66

77
using Statistics
88
import Statistics: mean
9+
using Random
910

1011
using Dates
1112

src/interval.jl

+10
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,16 @@ function _union(A::TypedEndpointsInterval{L1,R1}, B::TypedEndpointsInterval{L2,R
223223
Interval{L,R}(left, right)
224224
end
225225

226+
# random sampling from interval
227+
Random.gentype(::Type{Interval{L,R,T}}) where {L,R,T} = float(T)
228+
function Random.rand(rng::AbstractRNG, i::Random.SamplerTrivial{ClosedInterval{T}}) where {T<:Real}
229+
_i = i[]
230+
isempty(_i) && throw(ArgumentError("The interval should be non-empty."))
231+
a,b = endpoints(_i)
232+
t = rand(rng, float(T))
233+
return clamp(t*a+(1-t)*b, _i)
234+
end
235+
226236
ClosedInterval{T}(i::AbstractUnitRange{I}) where {T,I<:Integer} = ClosedInterval{T}(minimum(i), maximum(i))
227237
ClosedInterval(i::AbstractUnitRange{I}) where {I<:Integer} = ClosedInterval{I}(minimum(i), maximum(i))
228238

test/runtests.jl

+28
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,34 @@ struct IncompleteInterval <: AbstractInterval{Int} end
707707
@test clamp.([pi, 1.0, big(10.)], Ref(2..9.)) == [big(pi), 2, 9]
708708
end
709709

710+
@testset "rand" begin
711+
@test rand(1..2) isa Float64
712+
@test rand(1..2.) isa Float64
713+
@test rand(1..big(2)) isa BigFloat
714+
@test rand(1..(3//2)) isa Float64
715+
@test rand(Int32(1)..Int32(2)) isa Float64
716+
@test rand(Float32(1)..Float32(2)) isa Float32
717+
@test_throws ArgumentError rand(2..1)
718+
719+
i1 = 1..2
720+
i2 = 3e100..3e100
721+
i3 = 1..typemax(Float64)
722+
i4 = typemin(Float64)..typemax(Float64)
723+
i5 = typemin(Float64)..1
724+
for _ in 1:100
725+
rand(i1) in i1
726+
rand(i2) in i2
727+
rand(i3) in i3
728+
rand(i4) in i4
729+
rand(i5) in i5
730+
rand(i1,10) i1
731+
rand(i2,10) i2
732+
rand(i3,10) i3
733+
rand(i4,10) i4
734+
rand(i5,10) i5
735+
end
736+
end
737+
710738
@testset "IteratorSize" begin
711739
@test Base.IteratorSize(ClosedInterval) == Base.SizeUnknown()
712740
end

0 commit comments

Comments
 (0)