higher precision floating point using boost lib (higher then 16 digits)(使用 boost lib 的更高精度浮点数(高于 16 位))
问题描述
我正在模拟物理实验,所以我需要非常高的浮点精度(超过 16 位).我使用 Boost.Multiprecision,但是无论我尝试什么,我都无法获得高于 16 位的精度.我用C++和eclipse编译器运行模拟,例如:
I am running a simulation of physical experiments, so I need really high floating point precision (more than 16 digits). I use Boost.Multiprecision, however I can't get a precision higher than 16 digits, no matter what I tried. I run the simulation with C++ and eclipse compiler, for example:
#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 位数字之后是不正确的.为什么?
As you can see, after 16 digits it is incorrect. Why?
推荐答案
您的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
编译器不使用任意精度的浮点文字,而是使用 IEEE-754 doubles,它们具有有限精度.在这种情况下,与您所写数字最接近的 double
是:
The compiler does not use arbitrary-precision floating point literals, and instead uses IEEE-754 doubles, which have finite precision. In this case, the closest double
to the number you have written is:
0.1234567891234567837965840908509562723338603973388671875
并将其打印到小数点后 50 位确实可以提供您正在观察的输出.
And printing it to the 50th decimal does indeed give the output you are observing.
您想要的是从字符串构造任意精度的浮点数(演示)::>
What you want is to construct your arbitrary-precision float from a string instead (demo):
#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
这篇关于使用 boost lib 的更高精度浮点数(高于 16 位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 boost lib 的更高精度浮点数(高于 16 位)


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01