Skip to content

Commit 2c5ec63

Browse files
authored
Merge pull request #223 from JuliaDiff/ox/finally_restore
restore value to mutated input on error
2 parents c7a4624 + 141d58f commit 2c5ec63

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/grad.jl

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ function jacobian(fdm, f, x::Vector{<:Real}; len=nothing)
1515
ẏs = map(eachindex(x)) do n
1616
return fdm(zero(eltype(x))) do ε
1717
xn = x[n]
18-
x[n] = xn + ε
19-
ret = copy(first(to_vec(f(x)))) # copy required incase `f(x)` returns something that aliases `x`
20-
x[n] = xn # Can't do `x[n] -= ϵ` as floating-point math is not associative
21-
return ret
18+
try
19+
x[n] = xn + ε
20+
return copy(first(to_vec(f(x)))) # copy required incase `f(x)` returns something that aliases `x`
21+
finally
22+
x[n] = xn # Can't do `x[n] -= ϵ` as floating-point math is not associative
23+
end
2224
end
2325
end
2426
return (reduce(hcat, ẏs), )

test/grad.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,19 @@ using FiniteDifferences: grad, jacobian, _jvp, jvp, j′vp, _j′vp, to_vec
8484
@test J one(Matrix{T}(undef, size(J)))
8585
end
8686

87+
@testset "jacobian that throws errors" begin
88+
# https://github.com/JuliaDiff/FiniteDifferences.jl/issues/221
89+
fdm = central_fdm(5, 1)
90+
x = zeros(5)
91+
try
92+
jacobian(fdm, error, x)
93+
catch err
94+
@assert err isa ErrorException
95+
end
96+
# Make sure state of `x` is restored.
97+
@test x == zeros(5)
98+
end
99+
87100
@testset "multi vars jacobian/grad" begin
88101
rng, fdm = MersenneTwister(123456), central_fdm(5, 1)
89102

0 commit comments

Comments
 (0)