# Float64 error when using ForwardDiff.gradient for nested functions

**URL:** <https://discourse.julialang.org/t/float64-error-when-using-forwarddiff-gradient-for-nested-functions/50343>\
**Category:** Optimization (Mathematical)\
**Created:** [November 17, 2020, 11:22pm UTC](https://discourse.julialang.org/t/float64-error-when-using-forwarddiff-gradient-for-nested-functions/50343 "2020-11-17T23:22:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![yips](https://avatars.discourse-cdn.com/v4/letter/y/ce73a5/32.png) [@yips](https://discourse.julialang.org/u/yips)\
**Post date:** [November 17, 2020, 11:22pm UTC](https://discourse.julialang.org/t/float64-error-when-using-forwarddiff-gradient-for-nested-functions/50343/1 "2020-11-17T23:22:54Z")

</div>

I am trying to use ForwardDiff.gradient find the gradient of the following function:

> **function** loss\_test(x::Array{T,2},SecreteFuncs,pInf::Array{T,2},cmat::Array{T,2}) where {T \<: Real}  
> cmat\_sol = Findcss(x,SecreteFuncs,pInf,cmat)  
> loss = (sum(cmat\_sol[:])-5)^2  
> return loss  
> **end**

where

> **function** Findcss(muvec::Array{T,2},SecreteFuncs,pInf::Array{T,2},cmat::Array{T,2}) where {T \<: Real}  
> lb = zeros(eltype(cmat),length(cmat[:]),1)  
> ub = ones(eltype(cmat),length(cmat[:]),1).\*Inf  
> inner\_optimizer = GradientDescent()  
> res = optimize(c → f\_cssObjloss(c,muvec,SecreteFuncs,pInf), lb, ub,  
> 0.1.\*ones(eltype(cmat\_guess),length(cmat\_guess[:]),1), Fminbox(inner\_optimizer), autodiff = :forward)  
> css\_sol = reshape(Optim.minimizer(res),size(cmat\_guess))  
> return css\_sol  
> **end**

I have tested that the function loss\_test works i.e.

> using ForwardDiff  
> using Optim  
> f\_test = x → loss\_test(x,SecreteFuncs,pInf\_test,cmat\_test)  
> f\_test(mumaxvec)

gives the correct output.  
But when I try to take gradient:

> g\_test = x → ForwardDiff.gradient(f\_test, x)  
> g\_test(mumaxvec)

I get the following error:

> MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{var"#133#134",Real},Real,2}).

Is this because the output of Findcss is Float64? If so, how should I resolve this?

Any help would be greatly appreciated. Thanks!
