",round(n))浮動小数点値が一貫して丸められることを期待するかもしれません。"/> ",round(n))浮動小数点値が一貫して丸められることを期待するかもしれません。">

ホームページ  >  記事  >  バックエンド開発  >  浮動小数点丸めの結果が均一になるのはなぜですか?

浮動小数点丸めの結果が均一になるのはなぜですか?

Linda Hamilton
Linda Hamiltonオリジナル
2024-10-17 15:49:03824ブラウズ

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。