Skip to content

How to define random functions on your own types need to be better documented. #25605

@KristofferC

Description

@KristofferC

and have better error messages.

On 0.6:

julia> struct F
           v::Float64
       end

julia> rand(F)
ERROR: MethodError: no method matching rand(::MersenneTwister, ::Type{F})
Closest candidates are:
  rand(::AbstractRNG, ::Type, ::Tuple{Vararg{Int64,N}} where N) at random.jl:390
  rand(::AbstractRNG, ::Type, ::Integer, ::Integer...) at random.jl:391
  rand(::MersenneTwister, ::Type{I<:Base.Random.FloatInterval}) where I<:Base.Random.FloatInterval at random.jl:143
  ...
Stacktrace:
 [1] rand(::Type{T} where T) at ./random.jl:283

julia> Base.rand(::MersenneTwister, ::Type{F}) = F(rand())

julia> rand(F)
F(0.5219484358707998)

julia> rand(F, 2,2)
2×2 Array{F,2}:
 F(0.0131819)  F(0.0734573)
 F(0.440896)   F(0.735767)

The error message says exactly what is happening, I define the function, everything works.

On 0.7:

julia> struct F
           v::Float64
       end

julia> rand(F)
ERROR: ArgumentError: Sampler for this object is not defined
Stacktrace:
 [1] Type at ./random/random.jl:106 [inlined]
 [2] rand at ./random/random.jl:193 [inlined]
 [3] rand at ./random/random.jl:194 [inlined]
 [4] rand(::Type{F}) at ./random/random.jl:198
 [5] top-level scope

Ok... what do I do... Looking at docs for rand, says nothing about Sampler. Looking at NEWS.md, nothing about Sampler. Looking at docs, nothing about Sampler. Looking at >help? Sampler, No documentation found.. Let's try the same as in 0.6:

julia> Base.rand(::MersenneTwister, ::Type{F}) = F(rand())

julia> rand(F)
F(0.15546036169717214)

Woho, it works... or?

julia> rand(F, 2, 2)
ERROR: ArgumentError: Sampler for this object is not defined
Stacktrace:
 [1] Type at ./random/random.jl:106 [inlined]
 [2] rand at ./random/random.jl:193 [inlined]
 [3] rand! at ./random/random.jl:210 [inlined]
 [4] rand! at ./random/random.jl:206 [inlined]

Gives up.

Metadata

Metadata

Assignees

Labels

docsThis change adds or pertains to documentationrandomnessRandom number generation and the Random stdlib

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions