diff --git a/Project.toml b/Project.toml index 31c836cc..5f3ec55b 100644 --- a/Project.toml +++ b/Project.toml @@ -3,6 +3,7 @@ uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [deps] +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [compat] diff --git a/src/FixedPointNumbers.jl b/src/FixedPointNumbers.jl index 7f06c5d7..666ecb14 100644 --- a/src/FixedPointNumbers.jl +++ b/src/FixedPointNumbers.jl @@ -7,9 +7,10 @@ import Base: ==, <, <=, -, +, *, /, ~, isapprox, big, rationalize, float, trunc, round, floor, ceil, bswap, clamp, div, fld, rem, mod, mod1, fld1, min, max, minmax, signed, unsigned, copysign, flipsign, signbit, - rand, length + length import Statistics # for _mean_promote +import Random: Random, AbstractRNG, SamplerType, rand! using Base.Checked: checked_add, checked_sub, checked_div @@ -315,7 +316,7 @@ const UF = (N0f8, N6f10, N4f12, N2f14, N0f16) promote_rule(::Type{X}, ::Type{Tf}) where {X <: FixedPoint, Tf <: AbstractFloat} = promote_type(floattype(X), Tf) -# Note that `Tr` does not always have enough domains. +# Note that `Tr` does not always have enough domains. promote_rule(::Type{X}, ::Type{Tr}) where {X <: FixedPoint, Tr <: Rational} = Tr promote_rule(::Type{X}, ::Type{Ti}) where {X <: FixedPoint, Ti <: Integer} = floattype(X) @@ -382,8 +383,15 @@ scaledual(::Type{Tdual}, x::AbstractArray{T}) where {Tdual, T <: FixedPoint} = throw(ArgumentError(String(take!(io)))) end -rand(::Type{T}) where {T <: FixedPoint} = reinterpret(T, rand(rawtype(T))) -rand(::Type{T}, sz::Dims) where {T <: FixedPoint} = reinterpret(T, rand(rawtype(T), sz)) +function Random.rand(r::AbstractRNG, ::SamplerType{X}) where X <: FixedPoint + X(rand(r, rawtype(X)), 0) +end + +function rand!(r::AbstractRNG, A::Array{X}, ::SamplerType{X}) where {T, X <: FixedPoint{T}} + At = unsafe_wrap(Array, reinterpret(Ptr{T}, pointer(A)), size(A)) + Random.rand!(r, At, SamplerType{T}()) + A +end if VERSION >= v"1.1" # work around https://github.com/JuliaLang/julia/issues/34121 include("precompile.jl") diff --git a/test/common.jl b/test/common.jl index 6f8bc921..f8ae4a96 100644 --- a/test/common.jl +++ b/test/common.jl @@ -1,4 +1,4 @@ -using FixedPointNumbers, Statistics, Test +using FixedPointNumbers, Statistics, Random, Test using FixedPointNumbers: bitwidth, rawtype, nbitsfrac """ diff --git a/test/fixed.jl b/test/fixed.jl index 451a36ac..c37f54ba 100644 --- a/test/fixed.jl +++ b/test/fixed.jl @@ -436,6 +436,7 @@ end @test ndims(a) == 2 && eltype(a) === F @test size(a) == (3,5) end + @test rand(MersenneTwister(1234), Q0f7) === -0.156Q0f7 end @testset "Promotion within Fixed" begin diff --git a/test/normed.jl b/test/normed.jl index ff170434..40e69b3c 100644 --- a/test/normed.jl +++ b/test/normed.jl @@ -466,6 +466,7 @@ end @test ndims(a) == 2 && eltype(a) === N @test size(a) == (3,5) end + @test rand(MersenneTwister(1234), N0f8) === 0.925N0f8 end @testset "Promotion within Normed" begin