Go Down

Topic: Strange Variable Problem (Read 432 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