views:

239

answers:

1

Has anyone seen this weird value while handling sin / cos/ tan / acos.. math stuff?

===THE WEIRD VALUE===

-1.#IND00

=====================

void inverse_pos(double x, double y, double& theta_one, double& theta_two)
{
    // Assume that L1 = 350  and L2 = 250


    double B = sqrt(x*x + y*y);
    double angle_beta = atan2(y, x);
    double angle_alpha = acos((L2*L2 - B*B - L1*L1) / (-2*B*L1));
    theta_one = angle_beta + angle_alpha;
    theta_two = atan2((y-L1*sin(theta_one)), (x-L1*cos(theta_one)));
}

This is the code I was working on.

In a particular condition - like when x & y are 10 & 10, this code stores -1.#IND00 into theta_one & theta_two.

It doesn't look like either characters or numbers :(

Without a doubt, atan2 / acos / stuff are the problems.

But the problem is, try and catch doesn't work either cuz those double variables have successfully stored some values in them.

Moreover, the following calculations never complain about it and never break the program!

I'm thinking of forcing to use this value somehow and make the entire program crash... So that I can catch this error..

Except for that idea, I have no idea how I should check whether these theta_one and theta_two variables have stored this crazy values.

Any good ideas?

Thank you in advance..

+7  A: 

The "weird value" is NaN (not a number).

The problem is because (L2*L2 - B*B - L1*L1) / (-2*B*L1) = 6.08112… is outside of the range [-1, 1] where acos is well-defined for real numbers. So NaN is returned.

Are you sure the formula is correct?


If you want to catch an NaN, the NaN needs to be a signaling NaN. For gcc, compile with the -fsignaling-nans option.

KennyTM
Good answer, I've seen this in situations where you might *think* the input value is between -1 and 1 but in fact is the tiniest bit greater than 1 (due to rounding errors). You need to calculate the number first *then* force it into the range before passing it to acos. EG: double xx = (L2*L2...); if (xx >= 1) xx = 0.9999999999; or something like that.
paxdiablo
YOU GUYS ROCK!!! NaN was causing all the troubles!!I used to see NaN error msg in english and handled it.But not in this way. Thank all of you guys for your time!
Phrixus