부동 소수점 반올림이 결과가 균일한데 왜 놀라운가요?

Linda Hamilton
풀어 주다: 2024-10-17 15:49:03
원래의
823명이 탐색했습니다.

Why Does Float Rounding Surprise with Even Results?

Half Float Rounding-Up Dilemma

Encountering an oddity with the round() function? Observe the following behavior:

for i in range(1, 15, 2):
    n = i / 2
    print(n, "=>", round(n))
로그인 후 복사

You might expect the floating values to consistently round up, yet they surprisingly round to the nearest even number.

Reason Behind the Behavior

The documentation for Numeric Types clarifies this peculiar behavior with the statement "round(x[, n]) x rounded to n digits, rounding half to even." This is known as bankers rounding. Instead of persistent rounding up or down, which would amplify rounding errors, bankers rounding compensates by targeting the closest even number.

Solution for Controlled Rounding

To handle rounding precisely, leverage the decimal module. This module equips you with options to specify specific rounding strategies. For instance, to round up from half:

>>> from decimal import localcontext, Decimal, ROUND_HALF_UP
>>> with localcontext() as ctx:
...     ctx.rounding = ROUND_HALF_UP
...     for i in range(1, 15, 2):
...         n = Decimal(i) / 2
...         print(n, '=>', n.to_integral_value())
...
0.5 => 1
1.5 => 2
2.5 => 3
3.5 => 4
4.5 => 5
5.5 => 6
6.5 => 7
로그인 후 복사

위 내용은 부동 소수점 반올림이 결과가 균일한데 왜 놀라운가요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!