Mengapa Python Membundarkan Separuh Terapung kepada Nombor Genap?

Linda Hamilton
Lepaskan: 2024-10-17 15:53:29
asal
783 orang telah melayarinya

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>
Salin selepas log masuk

This code prints:

0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
Salin selepas log masuk

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>
Salin selepas log masuk

Output:

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

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!

sumber:php
Kenyataan Laman Web ini
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
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan