计算幅度 <1 和幅度 >1 时的精度损失
Accuracy loss when calculating magnitudes <1 with magnitudes >1
我正在测试字符串构建的gmp_float
。
#include <boost/multiprecision/number.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
typedef number<gmp_float<15>> mp_type;
int main()
{
mp_type total("1.01");
cout << total.str(0) << endl;
mp_type first_addition(".01");
cout << first_addition.str(0) << endl;
total += first_addition;
cout << total.str(0) << endl;
}
打印
1.01
0.01
1.01999999999999999998
为什么?我进行了更多的测试,在这种特殊情况下,只要一个数字的大小>0和<1,而另一个数字的大小>1,那么操作是什么并不重要。
从上面的链接
不可能将此类型的对象往返于字符串并返回完全相同的值。这似乎是GMP的限制。
是否有其他区域会失去准确性?
Boost Multiprecision也支持十进制浮点数:
查看Live On Coliru prints:
clang++ -std=c++11 -Os -Wall -pedantic main.cpp && ./a.out
1.01
0.01
1.02
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
using namespace boost::multiprecision;
using std::cout;
using std::endl;
typedef cpp_dec_float_50 mp_type;
int main()
{
mp_type total("1.01");
cout << total.str(0) << endl;
mp_type first_addition(".01");
cout << first_addition.str(0) << endl;
total += first_addition;
cout << total.str(0) << endl;
}
mpf_t
在GMP中是一个二进制浮点数。0.01
不能精确地表示为任何有限精度的二进制浮点数。
将0.01
更改为0.125
,将1.01
更改为1.125
,使格式化的输出看起来很好。这是因为0.125
和1.125
可以精确地表示为至少8位有效位的二进制浮点数。
相关文章:
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- int 到浮点转换的精度损失
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 在不损失精度的情况下将double从C++传输到python
- 禁止具有精度损失的整数转换
- 添加双精度时精度损失
- ceil、floor 和 round 在转换为整数时会遇到精度损失问题吗?
- 精度损失
- 精度损失(分配)
- 在C++中使用 pow 时精度损失
- 从浮子到双精度,从双精度到浮子的精度损失
- 将字符串转换为双精度,然后将双精度转换为字符串,而不会损失精度
- 处理在减去两个彼此接近的双精度时的精度损失
- 精度损失
- 在C++中将双精度转换为字符串时精度损失
- 在C++中标记双精度损失的算法不会标记正确的位置
- 如果可以接受一些精度损失,如何快速紧凑地保存双精度矩阵
- 编译器不会警告精度损失
- 这种精度损失发生在哪里以及如何防止
- 在 c++ 中将双精度转换为整数损失 1