subtraction problem?

I have the following function

1
2
3
4
5
6
7
8
9
10
11
12
13
void Robot::move(float theta, float distance)
{
std::cout << theta - (M_PI/2.0) << std::endl;  // <------ here the problem
    if (theta == 0.0)
    {
        this->m_x += distance;
    }

    else if ( theta == M_PI/2)
    {
        this->m_y += distance;
    }
}



and in the main function

1
2
3
4
5
 Robot myrobot;
    myrobot.set_position(10.0, 10.0, 0.0);
    myrobot.get_position();
    myrobot.move(M_PI/2.0, 10.0);
    myrobot.get_position();


This is what I got

[ x=10 y=10 heading=0 ]
4.37114e-08 <----------------( Why? )
[ x=10 y=10 heading=0 ]
I'm guessing M_PI is a double, or is defined with something like #define M_PI 3.13159

What you you are doing in myrobot.move(M_PI/2.0, 10.0) is converting a double to a float. That's going from a 64 bit number to a 32 bit number. You therefore lose precision. The you subtract the float from the double and you have a VERY small difference. That difference is attributed to the fact that we lost that much precision. In fact, depending on your warning level, the compiler is probably screaming out warnings at you.

As a general rule, never use the == operator on a floating point number (double or float) because it can become a VERY small number very fast without ever actually being exactly zero.
thank you. Can you tell me this problem under which section in programming field?
Topic archived. No new replies allowed.