Skip to content

Commit 1f15677

Browse files
Fix repeated evaluation of fx0 in forward gradient computation
- Moved fx0 computation outside the loop in finite_difference_gradient! - Optimizes function evaluations from 2N to N+1 for forward differences - Maintains compatibility with both cached and uncached function values - Simplifies logic by eliminating conditional branches in the main loop Fixes #202 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 83ff37e commit 1f15677

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

src/gradients.jl

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -372,37 +372,23 @@ function finite_difference_gradient!(
372372
end
373373
copyto!(c3, x)
374374
if fdtype == Val(:forward)
375+
fx0 = typeof(fx) != Nothing ? fx : f(x)
375376
for i in eachindex(x)
376377
epsilon = compute_epsilon(fdtype, x[i], relstep, absstep, dir)
377378
x_old = x[i]
378-
if typeof(fx) != Nothing
379-
c3[i] += epsilon
380-
dfi = (f(c3) - fx) / epsilon
381-
c3[i] = x_old
382-
else
383-
fx0 = f(x)
384-
c3[i] += epsilon
385-
dfi = (f(c3) - fx0) / epsilon
386-
c3[i] = x_old
387-
end
379+
c3[i] += epsilon
380+
dfi = (f(c3) - fx0) / epsilon
381+
c3[i] = x_old
388382

389383
df[i] = real(dfi)
390384
if eltype(df) <: Complex
391385
if eltype(x) <: Complex
392386
c3[i] += im * epsilon
393-
if typeof(fx) != Nothing
394-
dfi = (f(c3) - fx) / (im * epsilon)
395-
else
396-
dfi = (f(c3) - fx0) / (im * epsilon)
397-
end
387+
dfi = (f(c3) - fx0) / (im * epsilon)
398388
c3[i] = x_old
399389
else
400390
c1[i] += im * epsilon
401-
if typeof(fx) != Nothing
402-
dfi = (f(c1) - fx) / (im * epsilon)
403-
else
404-
dfi = (f(c1) - fx0) / (im * epsilon)
405-
end
391+
dfi = (f(c1) - fx0) / (im * epsilon)
406392
c1[i] = x_old
407393
end
408394
df[i] -= im * imag(dfi)

0 commit comments

Comments
 (0)