views:

96

answers:

1

Hello, Does anyone know of a python string-to-float parser that can cope with MSVC nan numbers (1.#QNAN)? Currently I'm just using float(str) which at least copes with "nan".

I'm using a python script to read the output of a C++ program (runs under linux/mac/win platforms) and the script barfs up when reading these values. (I did already find a C++ library to output the values consistently across platforms, but sometimes have to compare past results, so this still occaisionally pops up.)

+2  A: 

Since you have to deal with legacy output files, I see no other possibility but writing a robust_float function:

def robust_float(s):
    try:
        return float(s)
    except ValueError:
        if 'nan' in s.lower():
            return float('nan')
        else:
            raise
krawyoti
Well here is a funny part, my python (2.5 on win) does not support float('nan') but when i tried it on linux (2.4), it worked.Seems this depends on the C library as mentioned in help:`Note: When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary.`
Nas Banov
Thanks, that works.Regarding EnTerr's comment, I guess the easiest way to make it portable is to replace `float('nan')` with something like `1e1000-1e1000`.
dhardy
float('nan') is portable across platforms starting with 2.6. See http://docs.python.org/whatsnew/2.6.html
krawyoti