What's the best way to emulate single-precision floating point in python? (Or other floating point for开发者_如何学编程mats for that matter?) Just use ctypes?
numpy
has a float32
type.
If numpy
(the excellent suggestion of other answers) is inapplicable for you (e.g. because you're in an environment that doesn't allow arbitrary third-party extensions), the array module in Python standard library is fine too -- type code 'f'
gives you 32-bit floats. Besides those and the (usual) double precision floats, there isn't much for "other floating point formats" -- what did you have in mind? (e.g. gmpy
offers GMP's modest support for floats with much longer, arbitrary bit sizes -- but it's modest indeed, e.g., no trig functions).
It is possible to use Python's struct
module to truncate a 64-bit float to the precision of a 32-bit float.
For example:
>>> x = 1.1122334455667788
>>> x
1.1122334455667788
>>> struct.unpack('f', struct.pack('f', x))[0]
1.1122334003448486
To do arithmetic only with 32-bit floats, you would need to apply this truncation operation to the result of every arithmetic operation.
how about ctypes.c_float from standard library?
If your application suits arrays/matrices, you can use numpy with float32
To expand a little on the ctypes
option [1]:
>>> import ctypes
>>> ctypes.sizeof(ctypes.c_int)
4
>>> ctypes.sizeof(ctypes.c_long)
8
>>> ctypes.sizeof(ctypes.c_float)
4
>>> ctypes.sizeof(ctypes.c_double)
8
With numpy [2], e.g.:
>>> import numpy as np
>>> np.zeros((1,1), dtype='uint8').nbytes
1
>>> np.zeros((1,1), dtype='uint16').nbytes
2
>>> np.zeros((1,1), dtype='uint64').nbytes
8
>>> np.zeros((1,1), dtype='float').nbytes # watch out for this one
8
>>> np.zeros((1,1), dtype='float32').nbytes
4
>>> np.zeros((1,1), dtype='float64').nbytes
8
>>> np.zeros((1,1), dtype='single').nbytes
4
>>> np.zeros((1,1), dtype='double').nbytes
8
numpy.astype does conversions, e.g.
>>> np.zeros((1,1), dtype='double').astype('single').nbytes
4
[1] https://docs.python.org/3/library/ctypes.html#fundamental-data-types
[2] https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html
精彩评论