Edited to make it more specific
I would like to query status of the solution when using the Roots package, before the function returns an answer. I can see in the source code of “find_zero.jl” that it has some functionality state.convergence_failed = true
and also a function assess_convergence(method::Any, state::UnivariateZeroState{T,S}, options) where {T,S}
, but there is no documentation on how to use it. I have given a MWE and my attempts at resolving it below.
My questions is:
How to query the status of the solution before it returns a value? e.g. I would like to use the Schroder method first, and if it fails to converge then it should switch to Halley method. If the roots are complex or the algorithm fails to converge then it should return NaN.
using Roots
function root_func(c;guess=0.01,max_evals=100)
t = collect(0:length(c)-1)
f(x) = sum(@views c[i]/(1+x)^t[i] for i in 1:length(c))
#find derivatives of f(x)
df(x) = sum(@views -t[i]*c[i]/(1+x)^(t[i]+1) for i in 1:length(c))
ddf(x) = sum(@views (t[i]^2+t[i])*c[i]/(1+x)^(t[i]+2) for i in 1:length(c))
return find_zero((f,df,ddf),guess,Roots.Schroder();maxevals=max_evals)
end
Example usage:
root_func([-100,10,100,1,1]
My attempts at checking status of the solution before switching methods or returning a value are given here:
using Roots
function root_func(c;guess=0.01,max_evals=100)
t = collect(0:length(c)-1)
f(x) = sum(@views c[i]/(1+x)^t[i] for i in 1:length(c))
#find derivatives of f(x)
df(x) = sum(@views -t[i]*c[i]/(1+x)^(t[i]+1) for i in 1:length(c))
ddf(x) = sum(@views (t[i]^2+t[i])*c[i]/(1+x)^(t[i]+2) for i in 1:length(c))
r = find_zero((f,df,ddf),guess,Roots.Schroder();maxevals=max_evals)
if r.convergence_failed = false
return r
end
r = find_zero((f,df,ddf),guess,Roots.Halley();maxevals=max_evals)
if r.convergence_failed = false
return r
else return NaN
end
end