简体   繁体   English

浮点运算产生的数字基本上为零

[英]Floating point operations resulting in a number that is essentially zero

I'm doing some calculations that result in a value like {-0.707107, 9.61481e-017, 0.707107} when I'm expecting {-0.707107, 0, 0.707107}. 我正在做一些计算,当我期望{-0.707107,0,0.707107}时,得出的值类似于{-0.707107,9.61481e-017,0.707107}。 Could that second component, while essentially zero, cause problems down the road? 第二个成分虽然基本为零,但会在将来引起问题吗? Should I do something about it? 我应该为此做些什么吗? Using C++ doubles. 使用C ++双打。

That depends very much on what you intend to do down the road. 这在很大程度上取决于您打算在将来做什么。 :-) However, getting results that are very close to, but not exactly equal, to what the "mathematical" result should be, is something one must live with when using floating point numbers. :-)但是,使用浮点数必须获得与“数学”结果非常接近但不完全相等的结果。 A common solution is to define some "epsilon" value (say, 1e-10 ) and accept an error of epsilon in all comparisons - so x == y would become fabs(x - y) < epsilon . 常见的解决方案是定义一些“ε”值(例如1e-10 ),并在所有比较中接受epsilon的误差-因此x == y会变成fabs(x - y) < epsilon

They will only "cause problems" if you (a) are doing a numerically unstable calculation (you probably aren't) or (b) will later attempt to compare them using strict equality. 仅当您(a)进行数值不稳定的计算(您可能不是)或(b)稍后将尝试使用严格相等性比较它们时,它们才会“引起问题”。 In general, you shouldn't "do something" about it, you should just make sure that your algorithm is not overly sensitive to a small amount of imprecision. 通常,您不应对此“做任何事情”,而应确保算法对少量不精确度不过度敏感。

Yes they could cause problems, when comparing with 0. using == : that will return false . 是的,当与0.比较时,它们可能会引起问题。使用== :这将返回false Such rounding errors may also accumulate, as @driis noted. 如@driis所指出的,这种舍入误差也可能累积。

What you can do about this: instead of comparing using == , use a comparison that allows for round-off errors, and/or discard values that are below a reasonable threshold at appropriate points in the algorithm, depending on what you want to do with the values. 您可以做些什么:不要使用==进行比较,而是使用允许舍入误差的比较,和/或在算法中的适当点处舍弃低于合理阈值的值,具体取决于您要执行的操作与值。

See any good book on numerical algorithms. 参见任何有关数值算法的好书。

You can only safely use == for comparing floats for certain values and even then only when you have assigned those values directly, you can't use it for the result of any calcualtion. 您只能安全地使用==来比较某些值的浮点数,并且即使只有直接分配了这些值后,也不能将其用于任何计算结果。

normally you define a function 通常你定义一个函数

bool isEqual(double a,double b) {
  return fabs(a-b) < 0.0000001; // depends on the precision of your application
}

bool isClose(double a,double b) {
  return fabs(a-b) < 0.001;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM