Skip to content

AD in-place instead of broadcast #645

Closed
@b-fg

Description

@b-fg

I am sure this is covered somewhere and #136 (comment) is very much related, but I am struggling to understand why does this MWE work

addX!(a, x) = sum(a .+ x)
a = ones(10)
∂addX(a, x) = ForwardDiff.derivative(x -> addX!(a, x), x)
∂addX(a, 1.0)

but not this one:

function addX!(a, x)
    for i ∈ axes(a)
        a[i] += x
    end
    sum(a)
end

a = ones(10)
∂addX(a, x) = ForwardDiff.derivative(x -> addX!(a, x), x)
∂addX(a, 1.0)

With error: ERROR: MethodError: no method matching +(::Vector{Float64}, ::ForwardDiff.Dual{ForwardDiff.Tag{var"#5#6"{Vector{Float64}}, Float64}, Float64, 1})

What is special about broadcasting instead of explicitly writing the loop?
Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions