Christoph
Christoph

Reputation: 134

Angle to radians inaccuracy

I've written myself a tiny function that converts an angle into radians:

double toRadians(const double &angle){
    double radianangle = (double)(angle * M_PI) / 180;
    return radianangle;
}

Using this works just fine, however I am finding one problem. A quick test indicates that this is not completely accurate, here's what I did:

const double angle = 90;
double delta = toRadians(angle);
cout << "delta: " << delta << endl;
cout << "cosinus: " << cos(delta) << endl;
cout << "sinus: " << sin(delta) << endl;

This gives me the output:

delta: 1.5708
cosinus: 6.12323e-17
sinus: 1

While the correct value is given for the sinus in this case, it is obvious something is going wrong though, since cos(Pi/2) should be just 0. The inaccuracy is screwing up my entire graphics engine, so I would like to find a way to get rid of this.

Upvotes: 0

Views: 262

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

You always work with tolerances when using floating point numbers.

Instead of if (someDouble == 0.0) you do if (fabs(someDouble) < EPSILON).

Instead of if (someDouble == someOtherDouble) you do if (fabs(someDouble-someOtherDouble) < EPSILON).

EPSILON should be small enough for good accuracy, and big enough to account for floating point imprecision, e.g. constexpr const double EPSILON = 0.0001;.

See: Why Are Floating Point Numbers Inaccurate?

Upvotes: 3

Related Questions