bna*_*aya 6 c++ precision boost multiprecision
我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0.12345678912345678379658409085095627233386039733887
^
Run Code Online (Sandbox Code Playgroud)
但它应该是:
0.123456789123456789123456789
Run Code Online (Sandbox Code Playgroud)
如您所见,在16位数之后它是不正确的.为什么?
use*_*016 12
你的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
Run Code Online (Sandbox Code Playgroud)
编译器不使用任意精度浮点文字,而是使用具有有限精度的IEEE-754 双精度.在这种情况下,最接近double您编写的数字是:
0.1234567891234567837965840908509562723338603973388671875
Run Code Online (Sandbox Code Playgroud)
并将其打印到第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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
0.123456789123456789123456789
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |