[Numpy-discussion] annoying numpy string to float conversion behaviour

Torgil Svensson torgil.svensson at gmail.com
Thu Jun 21 17:48:38 EDT 2007


On 6/21/07, David M. Cooke <cookedm at physics.mcmaster.ca> wrote:
> On Jun 20, 2007, at 04:35 , Torgil Svensson wrote:
>
> > Hi
> >
> > Is there a reason for numpy.float not to convert it's own string
> > representation correctly?
>
> numpy.float is the Python float type, so there's nothing we can do. I
> am working on adding NaN and Inf support for numpy dtypes, though, so
> that, for instance, numpy.float64('-1.#IND') would work as expected.
> I'll put it higher on my priority list :-)

Great news. Thanks!

//Torgil


>
> > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > (Intel)] on win32>>> import numpy
> >>>> numpy.__version__
> > '1.0.3'
> >>>> numpy.float("1.0")
> > 1.0
> >>>> numpy.nan
> > -1.#IND
> >>>> numpy.float("-1.#IND")
> > Traceback (most recent call last):
> >  File "<pyshell#20>", line 1, in <module>
> >    numpy.float("-1.#IND")
> > ValueError: invalid literal for float(): -1.#IND
> >>>>
> >
> > Also, nan and -nan are represented differently for different float to
> > string conversion methods. I guess the added zeros are a bug
> > somewhere.
> >>>> str(nan)
> > '-1.#IND'
> >>>> "%f" % nan
> > '-1.#IND00'
> >>>> str(-nan)
> > '1.#QNAN'
> >>>> "%f" % -nan
> > '1.#QNAN0'
> >
> > This is a problem when floats are stored in text-files that are later
> > read to be numerically processed. For now I use the following to
> > convert the number.
> >
> > special_numbers=dict([('-1.#INF',-inf),('1.#INF',inf),
> >                       ('-1.#IND',nan),('-1.#IND00',nan),
> >                       ('1.#QNAN',-nan),('1.#QNAN0',-nan)])
> > def string_to_number(x):
> >    if x in special_numbers:
> >        return special_numbers[x]
> >    return float(x) if ("." in x) or ("e" in x) else int(x)
> >
> > Is there a simpler way that I missed?
> >
> > Best Regards,
> >
> > //Torgil
> > _______________________________________________
> > Numpy-discussion mailing list
> > Numpy-discussion at scipy.org
> > http://projects.scipy.org/mailman/listinfo/numpy-discussion
> >
>
> --
> |>|\/|<
> /------------------------------------------------------------------\
> |David M. Cooke              http://arbutus.physics.mcmaster.ca/dmc/
> |cookedm at physics.mcmaster.ca
>
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>
>



More information about the NumPy-Discussion mailing list