Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fallback randn/randexp for AbstractFloat #44714

Merged
merged 6 commits into from
Apr 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ Standard library changes

#### Random

* `randn` and `randexp` now work for any `AbstractFloat` type defining `rand` ([#44714]).

#### REPL

#### SparseArrays
Expand Down
6 changes: 4 additions & 2 deletions stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,10 @@ Sampler(rng::AbstractRNG, ::Type{X}, r::Repetition=Val(Inf)) where {X} =

typeof_rng(rng::AbstractRNG) = typeof(rng)

Sampler(::Type{<:AbstractRNG}, sp::Sampler, ::Repetition) =
throw(ArgumentError("Sampler for this object is not defined"))
# this method is necessary to prevent rand(rng::AbstractRNG, X) from
# recursively constructing nested Sampler types.
Sampler(T::Type{<:AbstractRNG}, sp::Sampler, r::Repetition) =
throw(MethodError(Sampler, (T, sp, r)))
Copy link
Member Author

@stevengj stevengj Mar 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this is a minor change, but a MethodError seems to be what is really desired here (and is what we normally throw in methods we've only defined to prevent infinite dispatch loops).

(Otherwise, some downstream tests in SparseArrays fail because randn now falls through to rand and throws a different error, so this seems like the least-breaking change.)


# default shortcut for the general case
Sampler(::Type{RNG}, X) where {RNG<:AbstractRNG} = Sampler(RNG, X, Val(Inf))
Expand Down
12 changes: 12 additions & 0 deletions stdlib/Random/src/normal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ randn(rng::AbstractRNG, ::Type{Complex{T}}) where {T<:AbstractFloat} =
Complex{T}(SQRT_HALF * randn(rng, T), SQRT_HALF * randn(rng, T))


### fallback randn for float types defining rand:
function randn(rng::AbstractRNG, ::Type{T}) where {T<:AbstractFloat}
# Marsaglia polar variant of Box–Muller transform:
while true
x, y = 2rand(rng, T)-1, 2rand(rng, T)-1
0 < (s = x^2 + y^2) < 1 && return x * sqrt(-2log(s)/s)
stevengj marked this conversation as resolved.
Show resolved Hide resolved
end
end

## randexp

"""
Expand Down Expand Up @@ -137,6 +146,9 @@ end
end
end

### fallback randexp for float types defining rand:
randexp(rng::AbstractRNG, ::Type{T}) where {T<:AbstractFloat} =
-log1p(-rand(rng, T))

## arrays & other scalar methods

Expand Down
38 changes: 29 additions & 9 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ let A = zeros(2, 2)
0.9103565379264364 0.17732884646626457]
end
let A = zeros(2, 2)
@test_throws ArgumentError rand!(MersenneTwister(0), A, 5)
@test_throws MethodError rand!(MersenneTwister(0), A, 5)
@test rand(MersenneTwister(0), Int64, 1) == [-3433174948434291912]
end
let A = zeros(Int64, 2, 2)
Expand Down Expand Up @@ -307,9 +307,32 @@ let a = [rand(RandomDevice(), UInt128) for i=1:10]
@test reduce(|, a)>>>64 != 0
end

# wrapper around Float64 to check fallback random generators
struct FakeFloat64 <: AbstractFloat
x::Float64
end
Base.rand(rng::AbstractRNG, ::Random.SamplerTrivial{Random.CloseOpen01{FakeFloat64}}) = FakeFloat64(rand(rng))
for f in (:sqrt, :log, :log1p, :one, :zero, :abs, :+, :-)
@eval Base.$f(x::FakeFloat64) = FakeFloat64($f(x.x))
end
for f in (:+, :-, :*, :/)
@eval begin
Base.$f(x::FakeFloat64, y::FakeFloat64) = FakeFloat64($f(x.x,y.x))
Base.$f(x::FakeFloat64, y::Real) = FakeFloat64($f(x.x,y))
Base.$f(x::Real, y::FakeFloat64) = FakeFloat64($f(x,y.x))
end
end
for f in (:<, :<=, :>, :>=, :(==), :(!=))
@eval begin
Base.$f(x::FakeFloat64, y::FakeFloat64) = $f(x.x,y.x)
Base.$f(x::FakeFloat64, y::Real) = $f(x.x,y)
Base.$f(x::Real, y::FakeFloat64) = $f(x,y.x)
end
end

# test all rand APIs
for rng in ([], [MersenneTwister(0)], [RandomDevice()], [Xoshiro()])
ftypes = [Float16, Float32, Float64]
ftypes = [Float16, Float32, Float64, FakeFloat64, BigFloat]
cftypes = [ComplexF16, ComplexF32, ComplexF64, ftypes...]
types = [Bool, Char, BigFloat, Base.BitInteger_types..., ftypes...]
randset = Set(rand(Int, 20))
Expand Down Expand Up @@ -406,15 +429,12 @@ for rng in ([], [MersenneTwister(0)], [RandomDevice()], [Xoshiro()])
rand!(rng..., BitMatrix(undef, 2, 3)) ::BitArray{2}

# Test that you cannot call randn or randexp with non-Float types.
for r in [randn, randexp, randn!, randexp!]
local r
for r in [randn, randexp]
stevengj marked this conversation as resolved.
Show resolved Hide resolved
@test_throws MethodError r(Int)
@test_throws MethodError r(Int32)
@test_throws MethodError r(Bool)
@test_throws MethodError r(String)
@test_throws MethodError r(AbstractFloat)
# TODO(#17627): Consider adding support for randn(BigFloat) and removing this test.
@test_throws MethodError r(BigFloat)

@test_throws MethodError r(Int64, (2,3))
@test_throws MethodError r(String, 1)
Expand Down Expand Up @@ -662,7 +682,7 @@ let b = ['0':'9';'A':'Z';'a':'z']
end

# this shouldn't crash (#22403)
@test_throws ArgumentError rand!(Union{UInt,Int}[1, 2, 3])
@test_throws MethodError rand!(Union{UInt,Int}[1, 2, 3])

@testset "$RNG() & Random.seed!(rng::$RNG) initializes randomly" for RNG in (MersenneTwister, RandomDevice, Xoshiro)
m = RNG()
Expand Down Expand Up @@ -734,8 +754,8 @@ end

struct RandomStruct23964 end
@testset "error message when rand not defined for a type" begin
@test_throws ArgumentError rand(nothing)
@test_throws ArgumentError rand(RandomStruct23964())
@test_throws MethodError rand(nothing)
@test_throws MethodError rand(RandomStruct23964())
end

@testset "rand(::$(typeof(RNG)), ::UnitRange{$T}" for RNG ∈ (MersenneTwister(rand(UInt128)), RandomDevice(), Xoshiro()),
Expand Down