0

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?

  • possible duplicate of [What is the best way to compare floats for almost-equality in Python?](http://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) – awesoon Dec 04 '14 at 07:32

2 Answers2

4

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • On Python 3 print(repr(rand)) and print(rand) are giving me the exact same output. – Scooter Dec 04 '14 at 07:41
  • AFAIK at least in Python3 `float.__str__` does try to provide a nicer output, however this output is defined as the shortest literal *that represents the given value*. So it wouldn't make any difference to type the other decimals. – Bakuriu Dec 04 '14 at 07:42
  • The question is clearly using Python 2 (because it uses `print rand` and not `print(rand)`). If you convert his program as-is to Python 3 (i.e., just change `print` and `raw_input`) then it already works. – BrenBarn Dec 04 '14 at 07:58
0

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"
theLeanDeveloper
  • 391
  • 4
  • 14