Confused on if statment

Krafter
Posts: 22
Joined: Wed Jan 27, 2016 11:36 pm

Confused on if statment

If confused here. I'm using python for my project. Below are two different versions of an if statement. One works properly and the other doesn't but really should behave the same. I'd really like to get example 2 to work.

current_time is a floating point.

Code: Select all

``if current_time >= 21.35 and current_time <= 21.37 then:``

Code: Select all

``````current_time_plus = current_time + .0002
if current_time >= 21.35 and current_ time <= current_time_plus then:
``````
example 1 works great but example 2 repeats if current_time is > 21.35 and above. Why? Like I said, I'm confused.

W. H. Heydt
Posts: 11064
Joined: Fri Mar 09, 2012 7:36 pm
Location: Vallejo, CA (US)

Re: Confused on if statment

Floating point numbers do not (generally speaking) have exact decimal equivalents, since that are binary (often hexadecimal0 in the form of a mantissa and exponent. In your second example, you are using so small a delta value that the conversion may not matter. Not to mention, your first example is check in a range 0.02 and your second example is using an increment of 0.0002...a hundred times smaller.

Krafter
Posts: 22
Joined: Wed Jan 27, 2016 11:36 pm

Re: Confused on if statment

Well I feel stupid on two different accounts. One is as you pointed out. I intended to add .02 to "current_time" and not .0002. The other reason is that "current_time" is continually updating. Therefore "current_time_plus" will never be less than current_time + .02...... Some minor rework and I'm sure I will get it working. Sorry to bother with such a dumb thing lol.

W. H. Heydt
Posts: 11064
Joined: Fri Mar 09, 2012 7:36 pm
Location: Vallejo, CA (US)

Re: Confused on if statment

Welcome to programming. When you get to point that you never feel stupid, you've stopped learning, so may as well ask someone to bury you. After 50+ years, I *still* make stupid mistakes, but I try to learn from them and move on.

Krafter
Posts: 22
Joined: Wed Jan 27, 2016 11:36 pm

Re: Confused on if statment

Lol. Thanks for that.