6

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?

4
  • 1
    Julia don't know which type you prefer among BigFloat, Float16, Float32 and Float64. Commented Oct 29, 2015 at 12:03
  • 1
    But for example one(AbstractFloat) gives either a Float32 or Float64 object depending on the system. Shouldn't rand have the same behaviour? Commented Oct 29, 2015 at 12:15
  • 1
    Good case, in my opinion, it's better for Julia to behave the same in alike situations, like the above. Commented Oct 29, 2015 at 13:07
  • Since rand(Float64) does not actually cover the whole range of Float64 values, but the [0,1) interval unlike the Int family, it seems reasonable to define this as an Abstract behavior and extend to AbstractFloat. Good point @Taiki Commented Oct 29, 2015 at 14:45

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very reasonable :) Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.