Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't rand work with AbstractFloat?

Tags:

julia

In Julia 0.4.0, when I try

rand(AbstractFloat, 1)

The following error is obtained:

ERROR: MethodError: `rand` has no method matching rand(::MersenneTwister,
::Type{AbstractFloat})

Is there a reason behind the fact that I must explicitly say Float32 or Float64 for rand to work? Or is it just that, as the language is relatively new, a relevant method has yet to be defined in the Base?

like image 956
Taiki Avatar asked Oct 29 '15 11:10

Taiki


1 Answers

one is different from rand. when using one(AbstractFloat), all the outputs are the "same":

julia> one(Float64)
1.0

julia> one(Float32)
1.0f0

julia> 1.0 == 1.0f0
true

this is not true when using rand:

julia> rand(srand(1), Float64)
0.23603334566204692

julia> rand(srand(1), Float32)
0.5479944f0

julia> rand(srand(1), Float32) == rand(srand(1), Float64)
false

this means if rand would behave like one, one might get two different results with the same seed on two different machines(e.g. one is x86, another is x64). take a look at the code in random.jl:

@inline rand{T<:Union{Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32}}(r::MersenneTwister, ::Type{T}) = rand_ui52_raw(r) % T

both rand(Signed)&rand(Unsigned) are illegal too.

like image 74
Gnimuc Avatar answered Nov 17 '22 12:11

Gnimuc