Chase down where in the loop the first NAN value is coming-from, because it's like the little "E(rror)" indicator in a pocket calculator. As soon as the value is "'not a number' anymore," all arithmetic stops. Write some debugging code that will
as soon as the NAN appears, so that you can find it. Then, a little more debugging stuff to trap where it actually occurs. Arithmetic overflow is a likely culprit but
the only possibility. Minimize guesswork.