Skip to content

Commit 460fc3d

Browse files
committed
make rand_tangent give only nice numbers
1 parent e776799 commit 460fc3d

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/rand_tangent.jl

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""
22
rand_tangent([rng::AbstractRNG,] x)
33
4-
Returns a randomly generated tangent vector appropriate for the primal value `x`.
4+
Returns a arbitary tangent vector _appropriate_ for the primal value `x`.
5+
Note that despite the name, no promises on the statistical randomness are made.
6+
Rather it is an arbitary value, that is generated using the `rng`.
57
"""
68
rand_tangent(x) = rand_tangent(Random.GLOBAL_RNG, x)
79

@@ -11,11 +13,20 @@ rand_tangent(rng::AbstractRNG, x::AbstractString) = NoTangent()
1113

1214
rand_tangent(rng::AbstractRNG, x::Integer) = NoTangent()
1315

14-
rand_tangent(rng::AbstractRNG, x::T) where {T<:Number} = randn(rng, T)
16+
# Try and make nice numbers with short decimal representations for good error messages
17+
# while also not biasing the sample space too much
18+
function rand_tangent(rng::AbstractRNG, x::T) where {T<:Number}
19+
return round(8randn(rng, T), sigdigits=6, base=2)
20+
end
21+
rand_tangent(rng::AbstractRNG, x::Float64) = rand(rng, -9:0.01:9)
22+
function rand_tangent(rng::AbstractRNG, x::ComplexF64)
23+
return ComplexF64(rand(rng, -9:0.1:9), rand(rng, -9:0.1:9))
24+
end
25+
1526

1627
# TODO: right now Julia don't allow `randn(rng, BigFloat)`
1728
# see: https://github.com/JuliaLang/julia/issues/17629
18-
rand_tangent(rng::AbstractRNG, ::BigFloat) = big(randn(rng))
29+
rand_tangent(rng::AbstractRNG, ::BigFloat) = big(rand_tangent(rng, Float64))
1930

2031
rand_tangent(rng::AbstractRNG, x::StridedArray) = rand_tangent.(Ref(rng), x)
2132
rand_tangent(rng::AbstractRNG, x::Adjoint) = adjoint(rand_tangent(rng, parent(x)))

test/rand_tangent.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,12 @@ using FiniteDifferences: rand_tangent
8686
@test x + rand_tangent(x) isa typeof(x)
8787
@test x + (rand_tangent(x) + rand_tangent(x)) isa typeof(x)
8888
end
89+
90+
@testset "niceness of printing" begin
91+
for i in 1:50
92+
@test length(string(rand_tangent(1.0))) <= 6
93+
@test length(string(rand_tangent(1.0 + 1.0im))) <= 12
94+
@test length(string(rand_tangent(1f0))) <= 12
95+
end
96+
end
8997
end

0 commit comments

Comments
 (0)