struct.unpack(struct.pack(float)) has roundoff error?
<p>When testing my library, <a href="https://github.com/construct/construct" rel="nofollow">Construct</a>, I found out that tests fail when numbers are built then parsed back to a float. Should floats not be represented exactly as in-memory floats?</p>

<pre><code>In [14]: d = struct.Struct("&lt;f")

In [15]: d.unpack(d.pack(1.23))
Out[15]: (1.2300000190734863,)
</code></pre>

<p>Floating point is inherently imprecise, but you are packing a double-precision float (<code>binary64</code>) into a single-precision (<code>binary32</code>) space there. See <a href="https://en.wikipedia.org/wiki/IEEE_floating_point#Basic_and_interchange_formats" rel="nofollow"><em>Basic and interchange formats</em></a> in the Wikipedia article on IEEE floating point formats; the Python <code>float</code> format uses double precision (see the <a href="https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex" rel="nofollow">standard types docs</a>; <em>Floating point numbers are usually implemented using double in C</em>).</p>

<p>Use <code>d</code> to use double precision:</p>

<pre><code>&gt;&gt;&gt; import struct
&gt;&gt;&gt; d = struct.Struct("&lt;d")
&gt;&gt;&gt; d.unpack(d.pack(1.23))
(1.23,)
</code></pre>

<p>From the <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow"><em>Format characters</em> section</a>:</p>

<blockquote>
  <p>format: <code>f</code>, C Type: <code>float</code>, Python type: <code>float</code>, Standard size: <code>4</code>, Footnote: (5)<br>
  format: <code>d</code>, C Type: <code>double</code>, Python type: <code>float</code>, Standard size: <code>8</code>, Footnote: (5)  </p>
  
  <ol start="5">
  <li>For the <code>'f'</code> and <code>'d'</code> conversion codes, the packed representation uses the IEEE 754 binary32 (for <code>'f'</code>) or binary64 (for <code>'d'</code>) format, regardless of the floating-point format used by the platform.</li>
  </ol>
</blockquote>

python floating-point pack