[Numpy-discussion] float16/32: wrong number of digits?

Anne Archibald peridot.faceted at gmail.com
Mon Mar 13 10:18:40 EDT 2017


On Mon, Mar 13, 2017 at 12:57 PM Eric Wieser <wieser.eric+numpy at gmail.com>
wrote:

> > `float(repr(a)) == a` is guaranteed for Python `float`
>
> And `np.float16(repr(a)) == a` is guaranteed for `np.float16`(and the same
> is true up to `float128`, which can be platform-dependent). Your code
> doesn't work because you're deserializing to a higher precision format than
> you serialized to.
>

I would hesitate to make this guarantee - certainly for old versions of
numpy, np.float128(repr(x))!=x in many cases. I submitted a patch, now
accepted, that probably accomplishes this on most systems (in fact this is
now in the test suite) but if you are using a version of numpy that is a
couple of years old, there is no way to convert long doubles to
human-readable or back that doesn't lose precision.

To repeat: only in recent versions of numpy can long doubles be converted
to human-readable and back without passing through doubles. It is still not
possible to use % or format() on them without discarding all precision
beyond doubles. If you actually need long doubles (and if you don't, why
use them?) make sure your application includes a test for this ability. I
recommend checking repr(1+np.finfo(np.longdouble).eps).

Anne

P.S. You can write (I have) a short piece of cython code that will reliably
repr and back long doubles, but on old versions of numpy it's just not
possible from within python. -A
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20170313/030de442/attachment.html>


More information about the NumPy-Discussion mailing list