This is just a style nitpick but it seems strange to call a small double precision epsilon-like variable `flag`.  Also I wonder if you really want `10e-300` or if you want `1e-300`, because the latter is more like `10**-300`.  Or maybe it's an approximation of the number near `1e-308` so the distinction would not be so important.