C++ Sgn Function
I saw the function below that shou开发者_如何学JAVAld return sign of double d. But I couldn't understand how it works?
int sgn(double d){
return d<-eps?-1:d>eps;
}
return d<-eps?-1:d>eps;
That means:
- If
d
is less than-eps
, the result is "negative" - If
d
is more thaneps
, the result is "positive" (d>eps
returns 1) - Otherwise we return 0 (meaning the number is "zero")
eps
would normally be a small number, so we consider numbers between, say -1e-5 and 1e-5 as "practically zero". This approach is used to water down some deficiencies of the computer's floating-point numbers, like that sin(pi)!=0
. However, it comes at the cost of introducing an arbitrary number eps
in the calculation, and losing the property that eg. if a
and b
are positive numbers, a*b
is positive provided underflow doesn't occur.
I suspect that eps is a very very small number, around 0.0000000001. If so, the function is using ternary notation to make an abbreviated form of:
int sgn(double d) { if (d < -eps) { return -1; } else { return d > eps; } }
That "return d > eps" part is probably there to make it return 0 if d == 0.0. Remember that expressions like "a > b" return boolean values, which become 1 if true or 0 if false.
So the function actually could return one of three values: -1 if the number is negative, 0 if it is zero, 1 if it is positive.
FLoating-point arithmetic has some peculiarities, like "machine epsilon" and -0
value. This solution uses machine epsilon to determine this '-0' case by using this machine epsilon, but is not completely correct: -0 = +0 = 0
, always, you don't have to check for it. Also, this eps
is not defined in your source: I guess It's defined elsewhere.
int sgn(double d){
return d<0? -1 : d>0; # -1, 0, +1. FIXED
}
much simpler, huh? :) in case d<0
it return -1
. Otherwise, d>0
gives either 0 or 1, like d>0? 1: 0
P.S. Usually you don't check check the equality of floats: they're not precise and 20.6
can suddently (predictable, actually) become 20.000000000001
. However, double
precision is very high with values close to zero.
I suppose that eps
is some very small value, really close to 0.
sgn
function returns -1 is the value is lower than -eps
, 0 if value is in [-eps,eps]
and 1 if value is greater than eps
.
eps is normally a very small value (greek letter epsilon is used in maths for a small increment)
So this says if the d is less than eps (eg. 0.00000001) return -1, else return 1 if it's greater than 0 and 0 if it's exactly 0
精彩评论