LoginSignup
1
0

【Python】エラー「decimal.DivisionUndefined」とは?DivisionByZeroとの違い

Posted at

概要

あまり見かけないPythonのエラーDivisionUndefinedに遭遇したので解説します。

サンプルコード

以下のコードを実行します。

from decimal import Decimal

sample = Decimal(0) / Decimal(0)
print(sample)

すると結果は以下の通り。

    sample = Decimal(0) / Decimal(0)
decimal.InvalidOperation: [<class 'decimal.DivisionUndefined'>]

解説

'decimal.DivisionUndefined'ってなんだ?って思って検索すると、これは除算の際に分子にも分母にも0(ゼロ)を連携した際に発生するエラーとのこと。

This occurs and signals invalid-operation if division by zero was attempted (during a divide-integer, divide, or remainder operation), and the dividend is also zero. The result is [0,qNaN].
引用元: https://tedboy.github.io/python_stdlib/generated/decimal.DivisionUndefined.html

似たようなエラーにdecimal.DivisionByZeroがあると思います。
どちらも0による除算を試みた際に発生するエラーですが、decimal.DivisionByZeroの方は分子が0でない場合に限ります。非ゼロの数値を0で除算しようとした時にのみ発生するエラーです。

一般的には0を0で割るケースなどあまりないので、DivisionByZeroの方が見かけるのかもしれません。

1
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
1
0