更高的precision浮点使用升压LIB(高于16位) [英] higher precision floating point using boost lib (higher then 16 digits)
问题描述
我正在运行的物理实验模拟,所以我需要非常高的浮点precision(超过16位)。我用Boost.Multi precision,但我不能得到比16位,无论什么我尝试了precision高。我运行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!
该编译器不使用arbitrary- precision浮点文字,而是使用IEEE-754的双打的,具有有限的precision。在这种情况下,最接近双击
来你写的数字是:
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.
你想要的是从字符串构建你arbitrary- precision浮动,而不是(演示)
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
这篇关于更高的precision浮点使用升压LIB(高于16位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!