gpt4 book ai didi

c++ - float 减法返回不正确的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:46 24 4
gpt4 key购买 nike

所以我有一个计算,减去作为 vector 对象组件的两个 float ,然后似乎返回了不正确的结果。

我尝试使用的代码是:

cout << xresult.x << " " << vec1.x << endl;
float xpart1 = xresult.x - vec1.x;
cout << xpart1 << endl;

运行此代码将返回的位置

16 17
-1.00002

如您所见,打印出 xresult.x 和 vec1.x 的值告诉您它们分别为 16 和 17,但减法运算似乎引入了错误。

有什么想法吗?

最佳答案

As you can see, printing out the values of xresult.x and vec1.x tells you that they are 16 and 17 respectively, yet the subtraction operation seems to introduce an error.

不,它根本没有告诉我们。它告诉我们输入值大约为 16 和 17。通常,不精确可能来自两个来源:浮点表示的性质,以及数字打印的精度。

输出流以一定的精度打印浮点值。来自 std::setprecision 的描述功能:

On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point.

因此,xresult.xvec1.x 的值分别为 16 和 17,精度为 5 位小数。事实上,一个略小于 16,另一个略大于 17。(请注意,这与不精确的浮点表示无关。声明 float f = 16float g = 17 都分配精确值。float 可以容纳精确的整数 16 和 17(尽管 float 不能容纳无限多的其他整数。) ) 当我们从略小于 16 中减去略大于 17 时,我们得到略大于负 1 的答案。

要向自己证明情况确实如此,请进行其中一个或两个实验。首先,在您自己的代码中,在打印这些值之前添加“cout << std::setprecision(10)”。二、运行这个测试程序

#include <iostream> 
#include <iomanip>

int main() {
for(int i = 0; i < 10; i++) {
std::cout << std::setprecision(i) <<
15.99999f << " - " << 17.00001f << " = " <<
15.99999f - 17.00001f << "\n";
}
}

注意输出的第 7 行如何匹配您的情况:

16 - 17 = -1.00002

附言所有其他关于不精确浮点表示的建议都是有效的,只是不适用于您的特定情况。您真的应该阅读“每位计算机科学家都应了解的浮点运算知识”。

关于c++ - float 减法返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5262889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com