1

To calculate the top left corner of the bounding box of a rotated rectangle (e.g. Calculate Bounding box coordinates from a rotated rectangle) I am trying to act differently based on the angle of rotation (to determine quadrants 0..90°..180°..270°..360°), given in degrees. The angle is convert to radians for the comparison with PI:

// http://codepad.org/zCxKJy30

#include <iostream>
#include "math.h"

using namespace std;

int main()
{
    float deg = 90.0;
    float rad = deg / 360.0 * 2.0 * M_PI;

    if( rad <= M_PI/2.0)
    {
        cout << "less or equal";
    }
    else
    {
        cout << "larger";
    }
    return 0;
}

I would expect the condition to be true, but it is not.

I was wondering if there is a simple solution, unlike How to compute correctly rounded trigonometric functions in degrees? and How can I account for round-off errors in floating-point arithmetic for inverse trig (and sqrt) functions (in C)? suggest.

I just tried using the double type and then the comparison works as expected: http://codepad.org/UHcee1RE

Why does increasing the precision result in the "correct" evaluation?

Community
  • 1
  • 1
handle
  • 5,859
  • 3
  • 54
  • 82
  • 1
    Possibly a duplicate of [Why are floating point numbers inaccurate](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate)? (I won't touch the maths with a ten-foot pole, but I strongly suspect that you are not aware of *how* limited the `float` type actually is...) – DevSolar Sep 18 '14 at 08:13
  • 4
    You're using double precision constants and arithmetic, but rounding to single precision. Using double precision throughout seems to give the correct result: http://coliru.stacked-crooked.com/a/8da13a49a98d34e5 – Paul R Sep 18 '14 at 08:14
  • Please consider, that neither `"math.h"` nor `M_PI` is standard C++. – Fytch Sep 18 '14 at 09:18
  • It your value is in degrees, why cant you compare it with 90 degrees? And yes, as mentioned before, floats are highly not recommended to be used nowadays, because of rounding during calculations. Use double instead, or fixed point calculations. And yes, keep in mind that any floating point values cannot be actually strictly compared , any particular floating point value actually means it hits some interval, but not equals a value. – NBR Sep 18 '14 at 10:42

0 Answers0