Go Down

Topic: Strange Variable Problem (Read 507 times) previous topic - next topic



I'm developing some software for an unmannned autonomous vehicle, and I've run into a very strange problem -- I have a float variable called "heading", and for testing purposes, I ended up with code like this:

if (heading == heading) {

The strange thing is, even though the first and last lines do print, the "Success" line doesn't! I initially wrote this code because the "heading" variable wasn't storing the proper value, and sort of out of desperation I just figured I would make sure that the variable itself was ok. Not sure where my logic was on that one, but it was late : P

Anyway, what would be a reason that a variable would not register as equal to itself?


Can it be because it's undefined ?


Good thought, but it's defined as a global variable:

float heading;

..earlier in the file (and given a value, albeit in a slightly complicated way, just before the test).


Erg, sorry about the trouble...it was one of those really annoying hard-to-spot programming mistakes.

Thanks though!


In general you can run into problems when you try to test for equality using floats, although it is strange that a float would not register the same as itself.  Try changing the code to see if it's close to itself:

if (heading > heading - 0.0001 && heading < heading + 0.0001)

I've used 0.0001 in my example, but you should choose something that's three or four orders of magnitude smaller than whatever is currently in "heading".

- Ben


it was one of those really annoying hard-to-spot programming mistakes.

Which was? :)


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131