I am trying to implement a 3-term recurrence relation: $$ p_{n+1} = ap_n + bp_{n-1} $$ This can be implemented as
p0 = P0 // starting value p_0
p1 = P1 // starting value p_1
loop n = 2,...,N
pn = a*p1 + b*p0
p0 = p1
p1 = pn
Depending on $(a,b)$ and also the stopping point $N$, this can sometimes overflow, and I would like to detect such a failure. I believe it is bad form to simply let the loop run to completion and then use something like isfinite
to check the final value.
A more elegant method would be to somehow test whether the term a*p1 + b*p0
will exceed the floating point maximum (DBL_MAX = 1.7976931348623157e+308
) prior to computing it. I could not find much information about this online, so does anyone have suggestions?
One idea I had, was suppose we are just dealing with the first term $a p_n$. Then we could test: $$ \log{|a p_n|} > \log{\textrm{DBL_MAX}} $$ or $$ \log{|a|} + \log{|p_n}| > \log{\text{DBL_MAX}} $$ It seems that this test would work even if $a p_n$ is not representable as a floating point number. I'm not sure how to extend this test to the general case $a p_n + b p_{n-1}$, or even if this test will account for all possible failure cases in double precision.