Cannot `convert` an object of type Random._GLOBAL_RNG to an object of type Random.MersenneTwister

Here is the error:

ERROR: LoadError: MethodError: Cannot `convert` an object of type Random._GLOBAL_RNG to an object of type Random.MersenneTwister
Closest candidates are:
  convert(::Type{S}, ::T) where {S, T<:CategoricalArrays.CategoricalValue} at /Users/logankilpatrick/.julia/packages/CategoricalArrays/nd8kj/src/value.jl:68
  convert(::Type{T}, ::T) where T at essentials.jl:171
  Random.MersenneTwister(::Any) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/Random/src/RNGs.jl:138
  ...
Stacktrace:

How would I define a convert function for this?

I think something like the following should be a sensible definition: Base.convert(::Type{MersenneTwister}, rng::Random._GLOBAL_RNG) = copy(rng).

Random._GLOBAL_RNG is the type of GLOBAL_RNG, which is now kind of a “proxy” for the thread-local global RNG, which you get via default_rng() (before Julia 1.3, GLOBAL_RNG was an MersenneTwister). In the definition above, copy(rng) is specialized for rng == GLOBAL_RNG, and simply returns copy(default_rng()).

2 Likes

That said, depending on the use-case, it might be enough to return Random.default_rng() without making a copy. Actually, it would be best that users don’t have to pirate-define this convert method, so it might be worthy opening a github issue.

2 Likes