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】Fraction型(分数)で値の比較はできるのか

Posted at

概要

Pythonで分数を扱う場合Pythonビルトインの分数を扱うfractionsパッケージについて軽く調べてみた。の記事で紹介されている、Fractionの機能が利用できます。これは四則演算やfloatへの変換もできる優れものなのですが、Fractionってできるのかなと少し調べてみたのでメモ書きします。

前提

  • 使用したPythonのバージョンは3.13.0です。

結論

Fractionでの比較は可能です。stackoverflowのHow to compare Fraction objects in Python?の回答を見ると、__eq__ __lt____gt__が実装されてるそう。

実装サンプル

いくつかケースを挙げて比較してみた実装サンプルを以下に記載します。

from fractions import Fraction

## 2/3の方が大きいのでTrueになる
print(Fraction(2, 3) > Fraction(1, 2))

## 1/3の方が大きいのでFalseになる
print(Fraction(1, 3) < Fraction(1, 5))

## 約分した結果で比較するのでTrueになる
print(Fraction(2, 4) == Fraction(1, 2))
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?