Python function function round analysis

Syntax : round(number[, ndigits])
The second ndigits parameter indicates which digit to round to. You need to calculate the original number before rounding. If you don't write it, it will be reserved to an integer by default.

>>> round(3.4)
3
>>> round(4.6)
5
>>> round(3.5)
4
>>> round(2.5)
2

Rule : round up to 50%

The round function does not behave the same in python 3 and 2

>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(1.5)
2
  • Official website documentation of python 2: https://docs.python.org/2/library/functions.html?highlight=round#round
    Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0).
    If it is the same distance from both ends, keep it to the side farther from 0. So round(0.5) will approximate to 1, and round(-0.5) will approximate to -1.
>>> round(0.5)
1.0
>>> round(-0.5)
-1.0

The result of the round of floats may surprise you, but it's not an error
Both python3 and 2 give the same example,
Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.

>>> round(2.675, 2)
2.67

The result is 2.67 instead of 2.68

This is not a bug: it is the fact that most fractional parts cannot be represented exactly as floating point numbers.

>>> print('{:.20f}'.format(2.675))
2.67499999999999982236

Look, 2.675 is printed with 20-digit precision, and the number 2.675 saved in the machine is a little smaller than the actual number. This makes it a little bit closer to 2.67, so rounding to two decimal places approximates 2.67.

summary:

  • The error mainly comes from when the input is converted from decimal to binary inside the computer.
  • round can round accurately, but the shift calculations it involves can introduce other errors as well.
  • Python's decimal package can be used to solve this problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325997021&siteId=291194637