You presumably get NaN (not a number) when you have an integer overflow on a 32-bit counter (i.e. a number larger than 2^31 - 1 = 2,147,483,647). Either you have a way to use 64 bbits counters or you may be you can use on of the modules for high prevision arithmetics such as BigInt.