Reputation: 1
I want to find the gradient of a function "lifetime_reward" by using ForwardDiff.gradient. "lifetime_reward" calls 4 other functions called "U", "U_prime", "steady_state" and "ramsey_simul".
function lifetime_reward(model, a::Vector, s::AbstractVector)::Number
Β = [model.β^i for i in range(1, 50, length=50)]
C = ramsey_simul(model, a, s)[4][2:51]
V = sum(Β.*C)
return V
end
U(x, model) = (x^(1-model.γ))/(1-model.γ)
U_prime(x, model) = x^(-model.γ)
function steady_state(model, a)
k_A = 1 - model.β*U_prime(1, model)*(1-model.δ)
k_B = model.β*U_prime(1, model)*model.α*exp(a)
k = k_A/k_B
k = k^(1/(model.α - 1))
y = exp(a)*(k^model.α)
i = k - (1-model.δ)k
c = y - i
return k, y, i, c
end
function ramsey_simul(model, a::Vector, s::AbstractVector)
T = length(a)
a0 = 0
ss = steady_state(model, a0)
k = ss[1]
y = ss[2]
i = ss[3]
c = ss[4]
V1 = [k]
V2 = [y]
V3 = [i]
V4 = [c]
for t=1:T
k = (1-model.δ)*k + i
y = exp(a[t])*(k^model.α)
i = y*s[t]
c = y - i
push!(V1, k)
push!(V2, y)
push!(V3, i)
push!(V4, c)
end
return V1, V2, V3, V4
end
I redefine lifetime_reward as function of s only :
lr(s) = lifetime_reward(model, a, s)
And then I try runnig this command :
ForwardDiff.gradient(lr, s_plot)
With :
s_plot = range(0.2, 0.3, length=50)
but this sends me :
MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{typeof(lr), Float64}, Float64, 10})
Closest candidates are:
(::Type{T})(::Real, !Matched::RoundingMode) where T<:AbstractFloat at rounding.jl:200
(::Type{T})(::T) where T<:Number at boot.jl:772
(::Type{T})(!Matched::AbstractChar) where T<:Union{AbstractChar, Number} at char.jl:50
...
Stacktrace:
[1] convert(#unused#::Type{Float64}, x::ForwardDiff.Dual{ForwardDiff.Tag{typeof(lr), Float64}, Float64, 10})
@ Base ./number.jl:7
[2] push!(a::Vector{Float64}, item::ForwardDiff.Dual{ForwardDiff.Tag{typeof(lr), Float64}, Float64, 10})
@ Base ./array.jl:1057
Can someone help me ? I am new to this package and not sure how its is working under the hood.
I guess this is a problem of type used and I bet my V1, V2, V3, V4 are not efficient in ramsey_simul. I already tried to change their types but what I did, dit not change the error.
Upvotes: 0
Views: 250