X=1 treated as X>1

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Andrea

it already happened a few times in my project:

if x<0 or x>1:

Would sometimes print “1”, even if i’st not possible (if x=1, it should print “OK”).
I suppose the actual value is slighlty superior to 1 and rounded in some weird way.
Similar stuff happened with 0 and -0
Note that x is a float variable.

What’s wrong with it?

:bust_in_silhouette: Reply From: jgodfrey

You’re most certainly being bitten by the print statement here. In that form, the value being printed (x) is converted to a string automatically. And, while I don’t know the details of how precision is handled in that case, your value is sufficiently close enough to 1 to simply be written as 1.

You can explicitly ask for more precision in the print statement by doing something like this:

print("%.15f" % [x])

That’ll print the value for x out to 15 decimal places (for example).

Ultimately, I’m confident that your value really is greater than 1. The default print mechanism just isn’t displaying it that way.

yep! that’s it, with your code it showed 1.0000000000000001

Andrea | 2020-05-12 14:53