0

In Python 3, I got a = 4.0000000000000001 b = 4.0000000000000002 since b>a, but while comparing a==b, it returns true and false on other two cases. I searched it on web and got an idea of converting them to string and then comparing them. but a=str(a) or repr(a) returns a='4.0' and b='4.0',I know why the repr fun is returning that but i want a='4.000000000000001' and b='4.000000000000002'.Can anyone help me? // Sorry for the poor english.

Madfish
  • 85
  • 6
  • 1
    Converting numbers to string to compare is *always* a bad idea. Now for your specific issue, you should learn about how floats work. They cannot represent all values you can type. – spectras Sep 03 '18 at 10:21
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – spectras Sep 03 '18 at 10:21
  • @spectras So is there any way i can have b>a ? – Madfish Sep 03 '18 at 10:32
  • 1
    Your `a` and `b` are the same value. As `float` does not have enough precision, the tiny bits at the end get truncated and you end up with `a == b == 4.0`. If you need more precision, you'll have to use another type, such as `Decimal`. – spectras Sep 03 '18 at 10:40
  • You should show specific code and data. Even disregarding the English, we do not know what it means that you got certain values for a and b since b>a. Were these values calculated? Written in Python source code? Converted from strings? Something else? How can we reproduce exactly the code you are asking about? – Eric Postpischil Sep 03 '18 at 18:06

0 Answers0