[plum.float] Tutorial: Using Float Types¶
The plum.float
subpackage provides plum type classes for packing and unpacking
floating point numbers. This tutorial teaches how to use the standard float plum types
offered as well as how to create custom float types.
Common Float Types¶
The plum.float
subpackage includes three modules, one for each endian
byte order: plum.float.big
, plum.float.little
, and plum.float.native
(native byte order follows host architecture). Each module provides plum type classes
for single and double precision floats:
Unpacking Bytes¶
The plum float types convert bytes into Python float
instances when used
with the various plum unpacking mechanisms. For example:
>>> from plum import unpack, Buffer
>>> from plum.float.big import Float32
>>>
>>> # utility function
>>> unpack(Float32, b'\x00\x00\x00\x00')
0.0
>>>
>>> # class method
>>> Float32.unpack(b'\x00\x00\x00\x00')
0.0
>>> # bytes buffer
>>> with Buffer(b'\x00\x00\x00\x00') as buffer:
... a = buffer.unpack(Float32)
...
>>> a
0.0
Packing Bytes¶
The plum float types convert floats (or anything float-like) into bytes when used with the various plum packing mechanisms. For example:
>>> from plum import pack
>>> from plum.float.big import Float32
>>>
>>> # utility function
>>> pack(Float32, 0.0)
bytearray(b'\x00\x00\x00\x00')
>>>
>>> # class method
>>> Float32.pack(0)
bytearray(b'\x00\x00\x00\x00')
>>>
>>> # instance method
>>> Float32(0).pack()
bytearray(b'\x00\x00\x00\x00')
Instantiation and Instance Properties¶
plum
float type constructors accept floats (or anything float()
accepts). The representation of the instance includes the class name to
differentiate it from standard Python float
instances:
>>> from plum.int.big import UInt8
>>>
>>> repr(Float32(0))
'Float32(0.0)'
Instances support the pack()
method:
>>> x = Float32(0)
>>> x.pack()
bytearray(b'\x00\x00\x00\x00')
Since plum
float types are a subclass of the standard Python
float
, they support the same behaviors and methods. For example:
>>> x = Float32(0)
>>>
>>> # compare
>>> x == 0
True
>>> # arithmetic
>>> x + 1
1.0
>>> # standard methods
>>> x.imag
0.0
>>> x.is_integer()
True
>>> x.real
0.0
Custom Float Types¶
The plum.float
subpackage offers the float
class for creating
float plum types for applications requiring packing and unpacking
unusually sized floats. The following example uses the nbytes
argument to create a half precision float:
>>> from plum.float import Float
>>>
>>> class Float16(Float, nbytes=2, byteorder='little'):
... """Half precision little endian floating point number."""
...
>>> Float16.unpack(b'\x00\x00')
0.0
>>>
>>> Float16.pack(0)
bytearray(b'\x00\x00')