ratnaveer
ratnaveer

Reputation: 71

How to get rid of minus sign from signed zero

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.

Upvotes: 7

Views: 7291

Answers (6)

mrtnhfmnn
mrtnhfmnn

Reputation: 407

Are you sure that signed zero is your problem? (In this case, adding 0.0 to it—as proposed by FacundoJ above—would in fact solve it. Provided your arithmetic conforms to IEEE 754, that is.)

If, on the other hand, your problem is that printf("%f", x) produces -0.000000 (or similar for a similar format specifier), then just adding 0.0 is not enough: you will get the same output for any small, but negative, value.

In this case some actual programming is needed (at least I know of no better solution). I used something like this the other day:

int snrfmt(char *s, const char *format, double x)
{
    int n, m;
    char z[32];

    n = sprintf(s, format, x);
    m = sprintf(z, format, -DBL_MIN);
    if (n == m && strcmp(s, z) == 0)
        n = sprintf(s, format, 0.0);
    return n;
}

as a kind-of replacement for sprintf():

double x = -1.23E-45;
char nr[80];

(void)snrfmt(buf, "%#+010.4f", x);
puts(nr);

This produces "+0000.0000" as desired (but of course "-0000.0001" for x = -0.50001E-4).

Upvotes: -1

talukm
talukm

Reputation: 19

You can use the following method.

 value = Float.compare(value, -0.0f) == 0 ? 0.0f : value ;

Upvotes: -1

javiergelatti
javiergelatti

Reputation: 431

You can do the following:

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

I had the same problem and that worked for me.

Upvotes: 12

CannibalSmith
CannibalSmith

Reputation: 4820

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

Upvotes: -1

kennytm
kennytm

Reputation: 523304

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;
}

Upvotes: 7

Matt Ellen
Matt Ellen

Reputation: 11592

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)

Upvotes: 2

Related Questions