在计算双精度值期间,错误计数增加
Errors count increasing during the calculation of double value
我正在进行一个计算,该计算将双精度转换为二进制,在此过程中发生了一个奇怪的问题,最终导致错误。因此,当我发现结果错误时,我打印出小数部分。
小数部分的代码如下:
while(float_part != (int)(float_part)){
float_part -= (int)(float_part); //just leave fractional part
float_part *= 2; //float_part is a double
res = res + to_string(((int)(float_part))); //add to "res", which is a string
cout << float_part << "+" << length << "n"; //to figure out why
length--; //the length is initialized to 32
if(length <= 0){
return "ERROR"; //if too long
}
}
然后我输入"28187281.525"(上面的代码中只有。525重要),发现结果很奇怪:
1.05+32
0.1+31
0.2+30
0.4+29
0.8+28
1.6+27
1.2+26
0.4+25
0.799999+24
1.6+23
1.2+22
0.399994+21
0.799988+20
1.59998+19
1.19995+18
0.399902+17
0.799805+16
1.59961+15
1.19922+14
0.398438+13
0.796875+12
1.59375+11
1.1875+10
0.375+9
0.75+8
1.5+7
1+6
1101011100001101010010001.100001100110011001100110011
一开始是好的,但最终结果是错误的!
为什么0.4*2变成0.799999.
有人知道原因吗?提前感谢!
浮点值具有有限的精度。对它们所做的任何操作都可能引入小错误。执行的操作越多,错误增加的就越多。在您的示例中,您应该将浮点变量拆分为整数组件(符号、尾数和指数),并对这些整数执行任何操作。浮点数通常以IEEE_754格式存储:
https://en.wikipedia.org/wiki/Floating_point IEEE_754: _floating_point_in_modern_computers
当您操作不能精确表示的值时,这是有限精度算术的本质。
0.4*2变成0.7999999,同样的道理,1/3乘以3变成0.9999999——你能做的最好的十进制是把1/3表示为0.333333,如果你把它乘以3,你得到0.99999。你需要无限个数字才能得到确切的答案。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- 数组索引的值没有增加
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 在网络套接字计时器滴答后增加asio短读错误
- 增加 gil 读取图像错误
- 增加图形转换错误
- 当我在C++中增加私有静态变量时,程序会抛出错误
- 在 solaris 上增加 1.64 构建错误
- 在Netbeans中增加LIB错误
- 不断增加的指针数组 错误:赋值中的类型不兼容
- 增加精神汇编错误
- 是否有可能通过增加编译器为数组提供的内存量来避免分段错误错误
- C++映射/设置迭代器在使用多映射时出现不可增加的错误
- 增加线程数时CUDA内核错误
- 在计算双精度值期间,错误计数增加
- C++adjacency_iterator增加图形库分割错误