0

while coding for a simple code of greater number, I get the output as the 1st number is greater whereas the greater number is the 2nd one

I have a small code of python where python doesn't recognize the greater number. Please help me to explain what is the case.

well if you look at the code then you will realize it's not a big deal but when you think about it in an atomic level you will know that the error is big.

a = 55.0000000000000009
b = 55.0

if (a > b):
  print("a is greater")
else:
  print("b is greater")

The actual output should be a is greater whereas it is showing the opposite.

Akhila
  • 3,235
  • 1
  • 14
  • 30
  • Note what's printed if you try to print `a`. `55.0000000000000009` can't be accurately represented. – Carcigenicate May 03 '19 at 15:42
  • 1
    I did a dumb retraction, so I can't reclose, but this would be a duplicate of https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Carcigenicate May 03 '19 at 15:43
  • I did not understand. explain it properly. I am new to the programming. – Codebreaker056 May 03 '19 at 15:45
  • Decimal numbers are stored as approximations. Not every possible number can be represented. The closest number to `55.0000000000000009` that can be stored is `55.0`, which is what `a` ends up holding. The link I posted to explain it far better than I can. – Carcigenicate May 03 '19 at 15:47
  • If you need complete accuracy to many decimal places, you need to use special types of numbers (often referred to something like a BigDecimal), or store it as an integer instead. – Carcigenicate May 03 '19 at 15:49
  • 3
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Joey May 03 '19 at 16:11
  • 1
    In this situation its``` a== b ```because they are close values – Akhila May 03 '19 at 16:52

1 Answers1

0

This should solve your problem

a = 55.0000000000000009
b = 55.0

if (a > b):
  print("a is greater")
elif (a < b):
  print("b is greater")
else:
  print("They are Equal")
azekkani
  • 39
  • 1
  • 5