简体   繁体   中英

Python - Float doesn't equal the same float?

So I have this:

import random

rand=random.random()
print rand

inp = raw_input("Enter your guess: ")
print float(inp)

try:
  if float(inp)==rand:
    print "equal"
  else:
    print "not equal"
except:
  print "error"

However it says it isn't equal. I know this is due to floating point inaccuracy, but how can I as a user input what come out to be equal?

Because you are using print on your float, it displays in a "nicer-looking" format that omits some decimal places. You can do print repr(rand) to show all the digits:

>>> rand = random.random()
>>> print rand
0.004312203809
>>> print repr(rand)
0.004312203809001436

If you use the latter form and then type all those numbers, you can get it to recognize the floats as equal.

Even you can use repr property

import random

rand=random.random()
print rand.__repr__()

inp = raw_input("Enter your guess: ")

print float(inp).__repr__()

try:
   if float(inp)==rand:
       print "equal"
   else:
       print "not equal"
except:
       print "error"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM