Skip to content

Tweak add_tiny #104

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

Merged
merged 3 commits into from
Jul 23, 2020
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: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "FiniteDifferences"
uuid = "26cc04aa-876d-5657-8c51-4c34ba976000"
version = "0.10.7"
version = "0.10.8"

[deps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Expand Down
4 changes: 3 additions & 1 deletion src/methods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ const DEFAULT_CONDITION = 100
"""
add_tiny(x::Real)

Add a tiny number, 10^{-20}, to `x` while preserving its type.
Add a tiny number, 10^{-20}, to `x`, preserving the type. If `x` is an `Integer`, it is
promoted to a suitable floating point type.
"""
add_tiny(x::T) where {T<:Real} = x + convert(T, 1e-20)
add_tiny(x::Integer) = add_tiny(float(x))

forward_grid(p::Int) = 0:(p - 1)
backward_grid(p::Int) = (1 - p):0
Expand Down
17 changes: 16 additions & 1 deletion test/methods.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
using FiniteDifferences: Forward, Backward, Central, Nonstandard
using FiniteDifferences: Forward, Backward, Central, Nonstandard, add_tiny

@testset "Methods" begin

@testset "add_tiny" begin
@test add_tiny(convert(Float64, 5)) isa Float64
@test add_tiny(convert(Float32, 5)) isa Float32
@test add_tiny(convert(Float16, 5)) isa Float16

@test add_tiny(convert(Int, 5)) isa Float64
@test add_tiny(convert(UInt, 5)) isa Float64
@test add_tiny(convert(Bool, 1)) isa Float64
end

# The different approaches to approximating the gradient to try.
methods = [forward_fdm, backward_fdm, central_fdm]

Expand Down Expand Up @@ -36,6 +46,11 @@ using FiniteDifferences: Forward, Backward, Central, Nonstandard
end
end

# Integration test to ensure that Integer-output functions can be tested.
@testset "Integer Output" begin
@test isapprox(central_fdm(5, 1)(x -> 5, 0), 0; rtol=1e-12, atol=1e-12)
end

@testset "Adaptation improves estimate" begin
@test forward_fdm(5, 1)(log, 0.001; adapt=0) ≈ 969.2571703
@test forward_fdm(5, 1)(log, 0.001; adapt=1) ≈ 1000
Expand Down