-5

I am a little confused about the Python's round function i tried some inputs and the function gives me interesting outputs. I am using Python 3.7.7 Can someone know why it is work like that ?

>>> round(2.505, 2)
2.5
>>> round(291.605, 2)
291.61
>>> round(291.705, 2)
291.7
>>> round(291.805, 2)
291.81
>>> round(291.405, 2)
291.4
ikibir
  • 456
  • 4
  • 12
  • 5
    See the official documentation before posting these types of questions https://docs.python.org/3/library/functions.html#round – ZWang Jul 20 '20 at 08:16
  • 1
    Maybe this will shed some light? https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Julien Jul 20 '20 at 08:24
  • @ZWang Well in the official documentation says round function for floats can be surprising and not really an explanation – ikibir Jul 20 '20 at 08:25
  • Then it redirects you to a page which explains why floating-point have limitations. @Julien linked a thread that explains the same phenomenon. Very interesting reads. – ZWang Jul 20 '20 at 08:28

1 Answers1

3

Floating point numbers are represented as binary fractions. Base 2 fractions.

Pyhton only displays decimal fractions based on the decimal approximation on the number stored by machine in binary fraction.

Most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

So 291.705 might be stored as 291.7049999997625792999286.. and so on. Thus resulting in 291.70 or 291.7

To learn more visit : Floating Point Arithmetic

Aagam Sheth
  • 685
  • 7
  • 15