백엔드 개발 파이썬 튜토리얼 round() 함수가 Python에서 숫자를 가장 가까운 짝수로 반올림하는 이유는 무엇입니까?

round() 함수가 Python에서 숫자를 가장 가까운 짝수로 반올림하는 이유는 무엇입니까?

Oct 17, 2024 pm 03:48 PM

Why Does round() Function Round Half Float Numbers to the Nearest Even Number in Python?

Understanding Half Float Number Rounding Behavior in Python

When dealing with half float numbers in Python, the round() function can exhibit an unexpected behavior, as illustrated by the following code snippet:

<code class="python">for i in range(1, 15, 2):
    n = i / 2
    print(n, "=&gt;", round(n))</code>
로그인 후 복사

This code prints:

0.5 =&gt; 0
1.5 =&gt; 2
2.5 =&gt; 2
3.5 =&gt; 4
4.5 =&gt; 4
5.5 =&gt; 6
6.5 =&gt; 6
로그인 후 복사

Instead of rounding up all floating values, round() rounds them to the nearest even number. This peculiar behavior is attributed to "rounding half to even," also known as "bankers rounding."

Cause of Bankers Rounding

According to the Python documentation, round() rounds half towards even to prevent compounding rounding errors. By rounding to the nearest even number, the overall rounding effect is averaged out.

Correcting the Rounding Behavior

To obtain the desired rounding behavior, specifically rounding up from half, the decimal module can be utilized. By defining a local context and setting the rounding parameter to ROUND_HALF_UP, Python's rounding function can be customized.

Here's an example demonstrating how to round up from half using the decimal module:

<code class="python">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, '=&gt;', n.to_integral_value())</code>
로그인 후 복사

The output of this code is:

0.5 =&gt; 1
1.5 =&gt; 2
2.5 =&gt; 3
3.5 =&gt; 4
4.5 =&gt; 5
5.5 =&gt; 6
6.5 =&gt; 7
로그인 후 복사

Conclusion

To achieve correct rounding behavior for half float numbers, the decimal module in Python provides the necessary tools for specifying the desired rounding strategy. By utilizing the ROUND_HALF_UP option, half float numbers can be rounded up consistently, as shown in the provided example.

위 내용은 round() 함수가 Python에서 숫자를 가장 가까운 짝수로 반올림하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Mar 05, 2025 am 09:58 AM

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법

파이썬에서 파일을 다운로드하는 방법 파이썬에서 파일을 다운로드하는 방법 Mar 01, 2025 am 10:03 AM

파이썬에서 파일을 다운로드하는 방법

파이썬의 이미지 필터링 파이썬의 이미지 필터링 Mar 03, 2025 am 09:44 AM

파이썬의 이미지 필터링

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? Mar 10, 2025 pm 06:54 PM

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까?

Python을 사용하여 PDF 문서를 사용하는 방법 Python을 사용하여 PDF 문서를 사용하는 방법 Mar 02, 2025 am 09:54 AM

Python을 사용하여 PDF 문서를 사용하는 방법

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Mar 02, 2025 am 10:10 AM

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법

NLTK (Natural Language Toolkit) 소개 NLTK (Natural Language Toolkit) 소개 Mar 01, 2025 am 10:05 AM

NLTK (Natural Language Toolkit) 소개

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Mar 10, 2025 pm 06:52 PM

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까?

See all articles