views:

225

answers:

3

I am using asin to calculate the angle. The code is as below :

double FindAngle(const double theValue)
{
     return asin(theValue);
}

FindAngle returns a -0.0 (signed zero), when the argument theValue = -0.0. Now, how do i get rid of the minus sign from the return value.

+3  A: 

include <cmath> and use the abs function on your return value, if you want all results to be positive, or check if your return value is equal to -0.0 and take the abs value of it, for just that case.

abs function (c++ reference)

Matt Ellen
if you apply abs() to your input value you are going to get the wrong result...
Mitch Wheat
Yeah, thanks. I realised my mistake. Have updated the answer.
Matt Ellen
+5  A: 

If you just want to convert -0 to 0 and leave other untouched, just do a comparison.

double FindAngle(double value) {
    double res = asin(value);
    if (res == 0.0) res = 0.0;
    return res;
}
KennyTM
I dont think comparing two doubles using "==" will always work
ratnaveer
comparisons on floating point values should be done with some precision, i.e. fabs(a - b) < epsilon. Using '==' is plain wrong.
MadH
It works for this case. I believe the asker only wants to convert `-0.0` to `0.0`, not an range of floats in `[-epsilon, 0]`. There is only one `-0.0`, and the only values `== 0.0` are `-0.0` and `0.0`, so the `==` can be used.
KennyTM
@MadH: It is absolutely not "plain wrong". In this case, any comparison using a threshold would be incorrect.
Stephen Canon
@yes, in this case threshold doesn't help; in order to solve a problem in place, one could divide by zero, then check which infinity it gives: +inf or -inf, and return fabs() in case of -inf
MadH
+1  A: 
double FindAngle(const double theValue)
{
    return abs(asin(value));
}
CannibalSmith