Go Down

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

glim

Hello,

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:

[font=Courier]Serial.println("---------TESTING");
if (heading == heading) {
   Serial.println("Success");
}
Serial.println("TESTING---------");[/font]


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?

melka

Can it be because it's undefined ?
http://melka.one.free.fr/blog/
http://www.flickr.com/photos/melkaone/

glim

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).

glim

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)
 serial.println("success");

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

follower

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

Which was? :)

--Phil.

Go Up