Inexact error with rand function

I have defined the following distribution

using Distributions,  Random

struct  ComplexNormal <:ContinuousUnivariateDistribution
    μ::ComplexF64
    σ::Float64
    function ComplexNormal(μ=0,σ=1) new(μ,σ) end
end

Base.rand(rng::AbstractRNG, d::ComplexNormal) =randn(ComplexF64)*d.σ+d.μ;

rand(ComplexNormal(1+2im,1)) generates a single element works.

rand(ComplexNormal(1+2im,1),2) (which should generate a vector of 2 elements) don’t quiet work, as it gives
InexactError: Float64(0.37414329354088083 + 1.039498256924925im)

I wonder how I can make this work.
One can certainly use list comprehension [rand(ComplexNormal()) for i=1:2]
But note that the following real counterpart works, it will be nice if the complex case also works.

using Distributions,  Random
struct  myNormal <:ContinuousUnivariateDistribution
    μ::ComplexF64
    σ::Float64
    function myNormal(μ=0,σ=1) new(μ,σ) end
end

Base.rand(rng::AbstractRNG, d::myNormal) = randn()*d.σ+d.μ;


rand(myNormal(1+2,1),2)
2-element Vector{Float64}:
 2.9376553287521845
 1.2461248703275385

However,

rand(myNormal(1+2im,1),2)
InexactError: Float64(1.621501920542256 + 2.0im)

and I noticed that in Julia, Real is not a subtype of Complex, I wonder if there is a reason behind not to make Real a subtype of Complex.

Thank you !

Define

Base.eltype(::Type{ComplexNormal}) = ComplexF64

so that Julia knows that the output type is ComplexF64 rather than Float64 (which is the default for continuous distributions).

See also this discussion: What problems will one have, if `Real` was made a subtype of `Complex`?

1 Like

Thank you for the solution!

The linked discussion is interesting, the post (which come up in the linked discussion) Abstract type between AbstractFloat and Real, answered my second question, and provided some insights in the development of Julia.