使用boost-lib的更高精度浮点(高于16位)
higher precision floating point using boost lib (higher then 16 digits)
我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过16位)。我使用Boost.Multiprecision,但无论我尝试什么,我都无法获得高于16位数的精度。我用C++和eclipse编译器运行模拟,例如:
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
using boost::multiprecision::cpp_dec_float_50;
void main()
{
cpp_dec_float_50 my_num= cpp_dec_float_50(0.123456789123456789123456789);
std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);
std::cout << my_num << std::endl;
}
输出为:
0.12345678912345678379658409085095627233386039733887
^
但它应该是:
0.123456789123456789123456789
正如你所看到的,在16位数字之后它是不正确的。为什么?
您的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
编译器不使用任意精度的浮点文字,而是使用精度有限的IEEE-754双精度。在这种情况下,最接近您所写数字的double
是:
0.1234567891234567837965840908509562723338603973388671875
将它打印到小数点后50位确实会得到你所观察到的输出。
你想要的是从字符串中构造任意精度的浮点值(演示):
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
using boost::multiprecision::cpp_dec_float_50;
int main() {
cpp_dec_float_50 my_num = cpp_dec_float_50("0.123456789123456789123456789");
std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);
std::cout << my_num << std::endl;
}
输出:
0.123456789123456789123456789
问题是C++编译器在编译时会将数字转换为双精度(我不久前也学到了这一点)。你必须使用特殊的函数来处理更多的小数点。有关示例,请参阅Boost文档或SO上的其他答案。
也就是说,几乎不可能真正需要如此高的精度。如果你正在失去精度,你应该考虑其他浮点算法,而不是盲目地增加小数位数。
相关文章:
- 将浮动的heightmap数组导出为16位原始值
- 宽度为奇数的16位纹理为片状
- OpenGL 16 位模板缓冲区?
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 16 位到 10 位转换代码说明
- AVX2 整数乘以有符号 8 位元素,产生有符号 16 位结果?
- C++将 16 位值转换为 32 位值
- 24 位地址和 24 位算术与 24 位地址与 16 位地址算术之间的区别?
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- 将 Uint8(浮点AUDIO_F32)转换为int16_t(16 位 PCM)
- AVX2 SIMD Instrinsics 16 位到 8 位,反之亦然
- 如何打开和读取16位.raw文件Vc++(Wince 平台)
- MongoDB C++ 驱动程序 - 8 位和 16 位整数?
- 使用 OpenCV 和 C++将 16 位灰度图像更改为彩色图像
- 对 32 位整数进行哈希处理比对 3 个 16 位整数的哈希进行按位运算慢?
- OpenCV 实感 16 位深度图像
- 有没有办法让32位C 编译器遵循16位整数促销规则
- 如何将 16 位无符号 int 转换为 8 位无符号字符并最终返回无符号字符*?
- 为什么16位编译器会给未知的char []声明提供错误
- 使用boost-lib的更高精度浮点(高于16位)