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}. Could that second component, while essentially zero, cause problems down the road? Should I do something 开发者_如何转开发about it? Using C++ doubles.
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
.
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. 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
. Such rounding errors may also accumulate, as @driis noted.
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;
}
精彩评论