Skip to content

Commit 9fce0ba

Browse files
committed
Issue 3288: document as_integer_ratio(), fromhex(), and hex().
1 parent d12dcae commit 9fce0ba

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

Doc/tutorial/floatingpoint.rst

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,39 @@ method's format specifiers in :ref:`formatstrings`.
138138
If you are a heavy user of floating point operations you should take a look
139139
at the Numerical Python package and many other packages for mathematical and
140140
statistical operations supplied by the SciPy project. See <http://scipy.org>.
141-
141+
142+
Python provides tools that may help on those rare occasions when you really
143+
*do* want to know the exact value of a float. The
144+
:meth:`float.as_integer_ratio` method expresses the value of a float as a
145+
fraction::
146+
147+
>>> x = 3.14159
148+
>>> x.as_integer_ratio()
149+
(3537115888337719L, 1125899906842624L)
150+
151+
Since the ratio is exact, it can be used to losslessly recreate the
152+
original value::
153+
154+
>>> x == 3537115888337719 / 1125899906842624
155+
True
156+
157+
The :meth:`float.hex` method expresses a float in hexadecimal (base
158+
16), again giving the exact value stored by your computer::
159+
160+
>>> x.hex()
161+
'0x1.921f9f01b866ep+1'
162+
163+
This precise hexadecimal representation can be used to reconstruct
164+
the float value exactly::
165+
166+
>>> x == float.fromhex('0x1.921f9f01b866ep+1')
167+
True
168+
169+
Since the representation is exact, it is useful for reliably porting values
170+
across different versions of Python (platform independence) and exchanging
171+
data with other languages that support the same format (such as Java and C99).
172+
173+
142174
.. _tut-fp-error:
143175

144176
Representation Error

0 commit comments

Comments
 (0)