Skip to content

Commit

Permalink
Merge pull request #223 from JuliaDiff/ox/finally_restore
Browse files Browse the repository at this point in the history
restore value to mutated input on error
  • Loading branch information
oxinabox authored Jun 7, 2023
2 parents c7a4624 + 141d58f commit 2c5ec63
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/grad.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ function jacobian(fdm, f, x::Vector{<:Real}; len=nothing)
ẏs = map(eachindex(x)) do n
return fdm(zero(eltype(x))) do ε
xn = x[n]
x[n] = xn + ε
ret = copy(first(to_vec(f(x)))) # copy required incase `f(x)` returns something that aliases `x`
x[n] = xn # Can't do `x[n] -= ϵ` as floating-point math is not associative
return ret
try
x[n] = xn + ε
return copy(first(to_vec(f(x)))) # copy required incase `f(x)` returns something that aliases `x`
finally
x[n] = xn # Can't do `x[n] -= ϵ` as floating-point math is not associative
end
end
end
return (reduce(hcat, ẏs), )
Expand Down
13 changes: 13 additions & 0 deletions test/grad.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ using FiniteDifferences: grad, jacobian, _jvp, jvp, j′vp, _j′vp, to_vec
@test J one(Matrix{T}(undef, size(J)))
end

@testset "jacobian that throws errors" begin
# https://github.com/JuliaDiff/FiniteDifferences.jl/issues/221
fdm = central_fdm(5, 1)
x = zeros(5)
try
jacobian(fdm, error, x)
catch err
@assert err isa ErrorException
end
# Make sure state of `x` is restored.
@test x == zeros(5)
end

@testset "multi vars jacobian/grad" begin
rng, fdm = MersenneTwister(123456), central_fdm(5, 1)

Expand Down

0 comments on commit 2c5ec63

Please sign in to comment.