python - 如何在 python 中将数字转换为 12 位精度?

标签 python types floating-point precision floating-accuracy

我需要在 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.

另请阅读有关使用此类奇异类型的注意事项

我发现这很有启发性。我的结论是,如果您想绝对保证 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/

相关文章:

python - 检查数字列表中是否存在数字

javascript - 未初始化值和未定义值之间的区别

c++ - C++中的类型和名称有什么区别?

c# - 为什么 double.IsNaN 有如此奇怪的实现

python - 如何在 Python Web 应用程序中启动 session ?

python - 解析csv文件并根据相对大小将行写入文件

python - 除以零错误

math - float 学坏了吗?

python - python中的关联组

python - 如何将我自己的 Meta 类与 SQLAlchemy-Model 一起用作父类