我需要在 Python 中存储一个 12 位精度的浮点变量
我知道要将变量转换为 float 有一个 float 函数,但我如何以位为单位指定 float 的大小?例如(12, 16, ...)
最佳答案
正如其他答案中提到的,这实际上并不存在 在纯 Python 数据类型中,see the docs
但是,您可以使用 numpy
来明确指定 data types例如
numpy.float16
numpy.float32
numpy.float64
您还可以使用 extended precision numpy.float96
这似乎是你想要的,例如 12 字节是 96 位
import numpy as np
high_prec_array = np.array([1,2,3], dtype=np.float96)
注意事项
正如评论和链接中所指出的,这不是真正的 12 字节精度。相反,80 位(10 字节)由 2 个零字节填充。如果您只关心兼容性,这可能就足够了。
这个精度may not be available on all platforms
In the tables below, platform? means that the type may not be available on all platforms. Compatibility with different C or Python types is indicated: two types are compatible if their data is of the same size and interpreted in the same way.
另请阅读有关使用此类奇异类型的注意事项
- https://stackoverflow.com/a/17023995/4013571
- https://mail.scipy.org/pipermail/scipy-dev/2008-March/008562.html
- https://www.reddit.com/r/learnpython/comments/3l7f3v/a_sneaky_numpy_feature_for_anyone_interested_in/
- https://stackoverflow.com/a/18537604/4013571
我发现这很有启发性。我的结论是,如果您想绝对保证 96bit
精度,那么 python
不是正确的选择,因为可用扩展精度中固有的歧义来自您的 C 分布中的歧义.鉴于你的物理背景,我建议使用 Fortran
如果你想保证稳定性。
用C++定义你自己的类型
对于感兴趣的高级用户,可以定义自己的数据类型。 user defined types states 上的 numpy
指南
As an example of what I consider a useful application of the ability to add data-types is the possibility of adding a data-type of arbitrary precision floats to NumPy.
因此您可以尝试使用 boost/multiprecision/cpp_bin_float.hpp
如果您热切希望将代码保存在 python
中。
关于python - 如何在 python 中将数字转换为 12 位精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573735/