Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

python - Python3 rounding to nearest even

Python3.4 rounds to the nearest even (in the tie-breaker case).

>>> round(1.5)
2
>>> round(2.5)
2

But it only seems to do this when rounding to an integer.

>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9

In the final example above, I would have expected 2.8 as the answer when rounding to the nearest even.

Why is there a discrepancy between the two behaviors?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Floating point numbers are only approximations; 2.85 cannot be represented exactly:

>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'

It is slightly over 2.85.

0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).

The round() function documents this explicitly:

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. See Floating Point Arithmetic: Issues and Limitations for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...