浮点数学运算后舍入不一致
Rounding is inconsistent after floating point math
以以下示例为例(带有人为的数字(:
double a = 9.0, b = 2.0;
double c = a / b;
int d = RoundAndCastToInt(c);
在多次运行中,d
的值不一致。以下是两种人为的数学执行方式:
执行 1:
9.0/2.0 == 4.49999...
RoundAndCastToInt(4.49999...( == 4
执行 2:
9.0/2.0 == 4.5
RoundAndCastToInt(4.5( == 5
我希望在不同的执行和不同的机器上一致地获得相同的值。在上面的示例中,只要始终4
或始终5
,4
或5
的结果就可以了。
对于
很多未解决的细节,这可能是愚蠢的,但我想当你知道你想要的解决方案的精度时,它可以工作......
#include <stdio.h>
#include <math.h>
int main(int argc, char * argv[]) {
float i = 5.3 / 4.7;
float j = 5.3 / 4.7;
printf("i %f n", round(i * 10000.0) / 10000.0);
printf("j %f n", round(j * 10000.0) / 10000.0);
return 0;
}
相关文章:
- OpenCV 细分一致的 Rect2f 到 Rect2i 舍入
- 将大 int 转换为浮点数,而不舍入 c++
- 浮点数学运算后舍入不一致
- C++长双精度格式而不舍入
- 为什么这个C++程序舍入双值而不打印整个字符串
- 对应该返回的双精度变量进行舍入,而不是打印
- C++舍入数字,不带上限或下限
- 不需要的舍入C++
- 浮点舍入不正确
- 如何在不舍入的情况下以C++显示固定位数
- cvRound() 中的 x64 舍入不一致 (_mm_cvtsd_si32)
- 清理值而不向上或向下舍入
- 舍入误差在DFT中给出不正确的tesult
- 不带逻辑运算符的舍入整数除法
- 当不需要时,C++双舍入
- 浮点数和由于舍入行为导致的不正确结果
- 用两个小数求3个数字的平均值(不舍入!)
- 在c++中,如何使用iostream和iomanip在不显示数字的情况下进行舍入?
- c++内部可以表示的0到1之间不舍入的最大和最小的数是什么?
- "floor"是否有可能由于浮点舍入误差而返回不准确的结果?