Stream: helpdesk (published)

Topic: forward finite differences


view this post on Zulip Dale Black (Sep 11 2021 at 23:47):

Is this the proper way of computing a simple forward difference algorithm in the x-direction in Julia, given h=1 on a 2D array/image?

image.png

function forward_diff_i(f)
    ∇ᵢ₊ = zeros(size(f))

    for j in 1:size(f, 2), i in 1:size(f, 1) - 1
        ∇ᵢ₊[i, j] = f[i + 1, j] - f[i, j]
    end

    # Compute backward diff for edge case
    for j in 1:size(f, 2)
        ∇ᵢ₊[end, j] = f[end, j] - f[end - 1, j]
    end

    return ∇ᵢ₊
end

If so, what's the recommended way to account for the edge?

view this post on Zulip Sundar R (Sep 12 2021 at 00:04):

have you looked at the difffunction in base Julia?

view this post on Zulip Dale Black (Sep 12 2021 at 00:09):

Oh no I hadn't actually. Looks like it's performing a similar operation and the results are similar on my end. Thanks

view this post on Zulip Dale Black (Sep 12 2021 at 00:26):

Here is what I have decided on, in case this is at all useful

function forward_diff_i(f)
    ∇ᵢ₊ = padarray(f, Pad(1, 1))

    for j in 1:size(f, 2), i in 1:size(f, 1)
        ∇ᵢ₊[i, j] = ∇ᵢ₊[i + 1, j] - ∇ᵢ₊[i, j]
    end

    return parent(∇ᵢ₊[1:end-1, 1:end-1])
end

view this post on Zulip Simon Christ (Sep 27 2021 at 09:43):

I'd consider renaming this topic to "forward differences" to not confuse it with forward mode automatic differentiation like implemented in ForwardDiff.jl

view this post on Zulip Mason Protter (Sep 27 2021 at 15:00):

Done


Last updated: Nov 06 2024 at 04:40 UTC