Automatic differentiation with a for loop in the function definition

Hi Julia community,

I am using Julia for my economics research and this is my first question posted here. Hopefully it is a simple one that more experienced users can easily answer.

I am trying to use automatic differentiation to compute the derivative of the two functions below.


function simplefunction_v1(x)    
    T = 3
    temp = x.^(0:T)
    return temp
end

function simplefunction_v2(x)    
    T = 3    
    temp = zeros(T+1)
    temp[1] = 1.0
    temp[2] = x
    for iT = 3:T+1
        temp[iT] = x*temp[iT-1]
    end
    return temp
end

These two functions return equivalent results for a scalar x. I run the following to use the ForwardDiff package to calculate the derivative of each function evaluated at x=2.0.

using ForwardDiff
ForwardDiff.derivative(simplefunction_v1,2.0)
ForwardDiff.derivative(simplefunction_v2,2.0)

While the second line (simplefunction_v1) above works as expected, I get an error from running the third line (simplefunction_v2).

It goes without saying that my actual application is quite a bit more involved, where I cannot get rid of the recursive relationship in the function definition. I would greatly appreciate any direction as to how to get the second version of the function working with automatic differentiation.

Thanks a lot.

is not generic. temp = zeros(eltype(x),T+1)

2 Likes

Perfect. Thank you!