0

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.

Christoph
  • 114
  • 1
  • 1
  • 10
  • 2
    Consider `6.12323e-17` as 0. You 're dealing with `double`. – DimChtz Apr 21 '18 at 21:54
  • 3
    I highly doubt that the discrepancy between 6e-17 and 0 could be "screwing up [your] entire graphics engine" – jeremyong Apr 21 '18 at 21:58
  • The problem lies in trying to look for bigger/smaller values. If it would give 0 then obviously it would be identified as equal. However this calculates differences that are like 4.2e-20. These aren't values i can use. – Christoph Apr 21 '18 at 22:03
  • 3
    `6.12323e-17` is 0.0000000000000000612323. The only way that this can cause a problem is if you're directly comparing floating point numbers, which you shouldn't do in the first place. Instead, always use tolerances. – eesiraed Apr 21 '18 at 22:05
  • The reason i chose to use them is because my image get's resized depending on the range of x and y values. So if all points would be in 0.5 difference or 200 difference, they would both get an appropriate image size. – Christoph Apr 21 '18 at 22:08
  • Possible duplicate of [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Max Vollmer Apr 21 '18 at 22:56
  • I'm voting to close this question as off-topic because the questioner does not understand how floating point numbers work. – duffymo Apr 22 '18 at 09:14

1 Answers1

3

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?

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43