-3

This is a pretty easy question.

I am doing a division of 1.2/0.2 on python 3.7.0 and I get 5.9999999999 instead of a clear 6. It is obvious that 1.2/0.2 is 6 so I don't understand why I am getting this result.

Thanks

GGChe
  • 193
  • 1
  • 1
  • 11
  • 1
    If you want to avoid such problems use [decimal](https://docs.python.org/3/library/decimal.html) built-in module – Daweo May 24 '21 at 14:33

1 Answers1

0

you can round a number, for example

round(1.2 / 0.2)

would give an answer of 6. The reason your getting this is due to floating point precision error.

It's a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.

you can read more here

  • cool, works for the moment. Anyway, it is very weird that python behave this way. – GGChe May 24 '21 at 14:40
  • Not really, most programming languages: Python, JavaScript, or C++ and many more, all have rounding errors when displaying floats. A float is actually stored as 3 integers, you have your exponent which is the whole number part of the float, for example `4.665` 4 would be the exponent, then you have the significand which is the decimal part `.665`. finally you have the sign `+` or `-`. –  May 24 '21 at 14:44
  • the rounding error is caused as a result of the way in which floats are stored in a computer. –  May 24 '21 at 14:44
  • thanks for the clarification Jared, very richen. – GGChe May 25 '21 at 14:00