简体   繁体   中英

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.

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, eg constexpr const double EPSILON = 0.0001; .

See: Why Are Floating Point Numbers Inaccurate?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM