Python, math.modfで数値の整数部と小数部を同時に取得
Posted: 2018-03-18 / Tags: Python
Pythonの数学関数の標準モジュールmath
のmodf()
関数を使うと、数値の整数部と小数部を同時に取得することができる。
割り算の商と余りを同時に取得するdivmod()
については以下の記事を参照。
スポンサーリンク
mathモジュールを使わずに整数部と小数部を取得
浮動小数点数float
型に対してint()
を適用すると、小数点以下を切り捨てた整数値が得られる。
これを使って、整数部と小数部を取得することができる。
a = 1.5
i = int(a)
f = a - int(a)
print(i)
print(f)
# 1
# 0.5
print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>
source: math_modf.py
math.modf()で数値の整数部と小数部を同時に取得
math
モジュールの関数modf()
で数値の整数部と小数部を同時に取得することができる。
math.modf()
は(小数部, 整数部)
のタプルを返す。小数部が先なので順番に注意。
import math
print(math.modf(1.5))
print(type(math.modf(1.5)))
# (0.5, 1.0)
# <class 'tuple'>
source: math_modf.py
以下のようにそれぞれをアンパックして別々の変数に代入することも可能。整数部も小数部もfloat
型。
f, i = math.modf(1.5)
print(i)
print(f)
# 1.0
# 0.5
print(type(i))
print(type(f))
# <class 'float'>
# <class 'float'>
source: math_modf.py
符号は整数部、小数部どちらも元の値の符号と同じになる。
f, i = math.modf(-1.5)
print(i)
print(f)
# -1.0
# -0.5
source: math_modf.py
int
型に対しても適用可能。この場合も、整数部も小数部もfloat
型。
f, i = math.modf(100)
print(i)
print(f)
# 100.0
# 0.0
source: math_modf.py
なお、float
型が整数(小数部が0)かどうかは小数部を取得しなくても、float
型のメソッドfloat.is_integer()
で確認することができる。以下の記事を参照。
- 関連記事: Pythonで数値が整数か小数かを判定
スポンサーリンク