浮点减法返回不正确的值 [英] Float subtraction returns incorrect value

查看:128
本文介绍了浮点减法返回不正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个计算,两个浮动是向量对象的组件被减去,然后似乎返回一个不正确的结果。

So I have a calculation whereby two floats that are components of vector objects are subtracted and then seem to return an incorrect result.

我试图使用是:

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.

任何想法为什么?

推荐答案

这称为浮点运算。这就是为什么数字代码是如此棘手,充满陷阱。这是预期的结果。更重要的是,它可以依赖于你正在处理的处理器,以及你将在什么程度上看到它。

This is called floating point arithmetic. It is why numerical code is so "tricky" and filled with pitfalls. That result is expected. And what is more, it can depend on the processor that you're working with as to what and to what extent you'll see it.

我想加上每种类型的变量的浮点变量:float,double,long double都有不同的精度因子。也就是说,可以更加精确地表示浮点数的值。

I'd like to add that each type of variable of the floating point variables: float, double, long double have different precision factors. That is, one may be more able to represent more accurately the value of the floating point number. That is evidenced by how these numbers are held in memory.

当你看一个浮点数时,它包含的数字比一个双精度或长双精度数字小。因此,当您对它们执行数字时,您必须预期浮点数将遭受更大的舍入误差。在处理财务数据时,开发人员经常使用一些十进制的相似性。这些更好地设计来处理具有更高的有效数字的准确性的货币类型操纵。

When you look at a float, it contains less significant digits than say a double or long double. Hence, when you perform numerics on them, you must expect that floats will suffer from larger rounding errors. When dealing with financial data, developers often use some semblance of a "decimal." These are much better designed to handle currency type manipulations with better accuracy of the significant digits. It comes with a price however.

请查看 IEEE 745-2008 规范。

这篇关于浮点减法返回不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆