""/> "">

Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Mengapa Python Membundarkan Separuh Terapung kepada Nombor Genap?

Mengapa Python Membundarkan Separuh Terapung kepada Nombor Genap?

Linda Hamilton
Linda Hamiltonasal
2024-10-17 15:53:29694semak imbas

Why Does Python Round Half-Floats to Even Numbers?

Rounding Half-Float Numbers

The round() function in Python exhibits an unusual behavior when rounding half floats that can be perplexing. Let's examine this behavior in more detail.

<code class="python">for i in range(1, 15, 2):
    n = i / 2
    print(n, "=>", round(n))</code>

This code prints:

0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6

Contrary to expectations, the floating values are not always rounded up. Instead, they are rounded to the nearest even number, even for half values. This behavior is documented in the Python documentation under "Numeric Types":

"round(x[, n])

x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0."

This rounding to the nearest even number, known as "bankers rounding," aims to mitigate rounding errors by averaging out the rounding.

To gain more control over rounding behavior, the decimal module offers a more flexible approach. The following example demonstrates 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, '=>', n.to_integral_value())</code>

Output:

0.5 => 1
1.5 => 2
2.5 => 3
3.5 => 4
4.5 => 5
5.5 => 6
6.5 => 7

By adjusting the rounding parameter within the localcontext(), you can customize rounding behavior as needed, ensuring accurate results for specific rounding scenarios.

Atas ialah kandungan terperinci Mengapa Python Membundarkan Separuh Terapung kepada Nombor Genap?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn