0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 3 エンジニア認定基礎試験 合格に向けて part2 (round() 関数)

0
Last updated at Posted at 2025-09-04

round() 関数は、Pythonで数値を四捨五入するための組み込み関数ですが、内部の動きは単純な「四捨五入」ではなく、銀行丸め(Banker's rounding) と呼ばれる少し特別なルールを使っています。


基本的な仕組み

  1. 引数がひとつの場合(round(x)

    • 小数第1位を基準に丸める(整数にする)。
    • 0.5 の場合は「偶数に丸める」。
    >>> round(3.5)
    4     # 偶数に丸める
    >>> round(4.5)
    4     # 偶数に丸める(普通の四捨五入だと5になりそうだが…)
    >>> round(3.6)
    4
    >>> round(3.4)
    3
    

    この「0.5を常に偶数に丸める」ルールが Banker's rounding(偶数丸め) です。
    こうすると、統計計算や大量データ処理で丸め誤差が偏りにくくなります。

  2. 引数がふたつの場合(round(x, ndigits)

    • ndigits の桁数に丸める。
    • ndigits=0 なら整数、ndigits=2 なら小数第2位まで。
    • 0.5 の場合はやはり偶数丸め。
    >>> round(2.675, 2)
    2.67   # 浮動小数点の影響で一見変な結果に見える
    >>> round(2.685, 2)
    2.68
    

    ここで「おや?」と思うのは、浮動小数点誤差の影響です。
    2.675 は内部では厳密に2.675ではなく、2.674999999... と表現されるため、結果が少しずれることがあります。


実装イメージ(概念)

  1. 値を10^n倍する(丸めたい桁数に合わせる)
  2. 0.5 の場合は偶数に丸める
  3. 10^n で割り戻す

まとめ

  • round() は「四捨五入」ではなく「偶数丸め(Banker's rounding)」
  • 大量のデータを丸めるときに偏りが減るのがメリット
  • 浮動小数点の誤差で直感と違う結果が出ることもある
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?