@@ -423,6 +423,71 @@ Notes:
423423
424424.. _typeiter :
425425
426+
427+ Additional Methods on Float
428+ ---------------------------
429+
430+ The float type has some additional methods to support conversion to
431+ and from hexadecimal strings. Since Python's floats are stored
432+ internally as binary numbers, converting a float to or from a
433+ *decimal * string usually involves a small rounding error. In
434+ contrast, hexadecimal strings allow exact representation and
435+ specification of floating-point numbers. This can be useful when
436+ debugging, and in numerical work.
437+
438+
439+ .. method :: float.hex()
440+
441+ Return a representation of a floating-point number as a hexadecimal
442+ string. For finite floating-point numbers, this representation
443+ will always include a leading ``0x `` and a trailing ``p `` and
444+ exponent.
445+
446+
447+ .. method :: float.fromhex(s)
448+
449+ Class method to return the float represented by a hexadecimal
450+ string *s *. The string *s * may have leading and trailing
451+ whitespace.
452+
453+
454+ Note that :meth: `float.hex ` is an instance method, while
455+ :meth: `float.fromhex ` is a class method.
456+
457+ A hexadecimal string takes the form::
458+
459+ [sign] ['0x'] integer ['.' fraction] ['p' exponent]
460+
461+ where the optional ``sign `` may by either ``+ `` or ``- ``, ``integer ``
462+ and ``fraction `` are strings of hexadecimal digits, and ``exponent ``
463+ is a decimal integer with an optional leading sign. Case is not
464+ significant, and there must be at least one hexadecimal digit in
465+ either the integer or the fraction. This syntax is similar to the
466+ syntax specified in section 6.4.4.2 of the C99 standard, and also to
467+ the syntax used in Java 1.5 onwards. In particular, the output of
468+ :meth: `float.hex ` is usable as a hexadecimal floating-point literal in
469+ C or Java code, and hexadecimal strings produced by C's ``%a `` format
470+ character or Java's ``Double.toHexString `` are accepted by
471+ :meth: `float.fromhex `.
472+
473+
474+ Note that the exponent is written in decimal rather than hexadecimal,
475+ and that it gives the power of 2 by which to multiply the coefficient.
476+ For example, the hexadecimal string ``0x3.a7p10 `` represents the
477+ floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10 ``, or
478+ ``3740.0 ``::
479+
480+ >>> float.fromhex('0x3.a7p10')
481+ 3740.0
482+
483+
484+ Applying the reverse conversion to ``3740.0 `` gives a different
485+ hexadecimal string representing the same number::
486+
487+ >>> float.hex(3740.0)
488+ '0x1.d380000000000p+11'
489+
490+
426491Iterator Types
427492==============
428493
0 commit comments