我对在浮点运算中舍入到最接近有点困惑。设a,b和c为归一化双精度浮点数。 a + b = b + a是否正确舍入为最接近的浮点加法?我最初的猜测是肯定的,这总是正确的,但我并不完全理解四舍五入到最近。有人可以给出一个例子,当a + b!= b + a时使用浮点加法和舍入到最近?
答案 0 :(得分:3)
正确实现的IEEE-754浮点加法是可交换的(a + b等于b + a),无论舍入模式如何。
舍入模式会影响精确数学结果的舍入方式,以适应目标格式。由于a + b和b + a的精确数学结果是相同的,因此它们是相同的。
答案 1 :(得分:0)
如上所述,添加是可交换的但不是关联的。通过运行以下(MS Visual Studio)C ++代码可以看出舍入模式的不同之处:
#include <iostream>
#include <float.h>
#pragma fenv_access(on)
using namespace std;
int main(int argc, char* argv[])
{
float a = 1.75f, b = 1e-6f;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(7);
cout << "a = " << a << ", b = " << b << endl;
_controlfp_s(NULL, _RC_DOWN,_MCW_RC);
cout << "Result of a + b rounded down: " << a+b << endl;
cout << "Result of a - b rounded down: " << a-b << endl;
_controlfp_s(NULL, _RC_UP,_MCW_RC);
cout << "Result of a + b rounded up: " << a+b << endl;
cout << "Result of a - b rounded up: " << a-b << endl;
_controlfp_s(NULL, _RC_NEAR,_MCW_RC);
cout << "Result of a + b rounded to nearest: " << a+b << endl;
cout << "Result of a - b rounded to nearest: " << a-b << endl;
return 0;
}
输出:
a = 1.7500000, b = 0.0000010
Result of a + b rounded down: 1.7500010
Result of a - b rounded down: 1.7499989
Result of a + b rounded up: 1.7500011
Result of a - b rounded up: 1.7499990
Result of a + b rounded to nearest: 1.7500010
Result of a - b rounded to nearest: 1.7499990