Skip to content

Commit ed63302

Browse files
committed
implement rand
1 parent ccb4267 commit ed63302

File tree

4 files changed

+25
-1
lines changed

4 files changed

+25
-1
lines changed

src/FixedPointNumbers.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import Base: ==, <, <=, -, +, *, /, ~, isapprox,
1010
zero, one, typemin, typemax, realmin, realmax, eps, sizeof, reinterpret,
1111
float, trunc, round, floor, ceil, bswap,
1212
div, fld, rem, mod, mod1, rem1, fld1, min, max, minmax,
13-
start, next, done, r_promote, reducedim_init
13+
start, next, done, r_promote, reducedim_init, rand
1414

1515
if VERSION <= v"0.5.0-dev+755"
1616
macro pure(ex)
@@ -161,4 +161,7 @@ showcompact{T,f}(io::IO, x::FixedPoint{T,f}) = show(io, round(Float64(x), ceil(I
161161
throw(ArgumentError("$T is $bitstring type representing $n values from $Tmin to $Tmax; cannot represent $x"))
162162
end
163163

164+
rand{T<:FixedPoint}(::Type{T}) = reinterpret(T, rand(rawtype(T)))
165+
rand{T<:FixedPoint}(::Type{T}, sz::Dims) = reinterpret(T, rand(rawtype(T), sz))
166+
164167
end # module

src/fixed.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ end
1111

1212
typealias Fixed16 Fixed{Int32, 16}
1313

14+
reinterpret{T<:Signed, f}(::Type{Fixed{T,f}}, x::T) = Fixed{T,f}(x, 0)
15+
1416
rawtype{T,f}(::Type{Fixed{T,f}}) = T
1517
nbitsfrac{T,f}(::Type{Fixed{T,f}}) = f
1618
floattype{T<:Fixed}(::Type{T}) = floattype(supertype(T))

test/fixed.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,11 @@ show(iob, x)
113113
str = takebuf_string(iob)
114114
@test startswith(str, "Fixed{Int32,3}(")
115115
@test eval(parse(str)) == x
116+
117+
for T in (Fixed{Int8,8}, Fixed{Int16,8}, Fixed{Int16,10}, Fixed{Int32,16})
118+
a = rand(T)
119+
@test isa(a, T)
120+
a = rand(T, (3, 5))
121+
@test isa(a, Array{T,2})
122+
@test size(a) == (3,5)
123+
end

test/ufixed.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,3 +277,14 @@ for T in (Float16, Float32, Float64, BigFloat)
277277
y = convert(T, x)
278278
@test isa(y, T)
279279
end
280+
281+
for T in (UFixed{UInt8,8}, UFixed{UInt8,6},
282+
UFixed{UInt16,16}, UFixed{UInt16,14},
283+
UFixed{UInt32,32}, UFixed{UInt32,30},
284+
UFixed{UInt64,64}, UFixed{UInt64,62})
285+
a = rand(T)
286+
@test isa(a, T)
287+
a = rand(T, (3, 5))
288+
@test isa(a, Array{T,2})
289+
@test size(a) == (3,5)
290+
end

0 commit comments

Comments
 (0)