LoginSignup
1
1

More than 3 years have passed since last update.

IDLEでPython3:数値編

Last updated at Posted at 2019-05-23

 ここでは,Python3における数値の扱いについてまとめていきます.よろしくお願いいたします.

 Pythonドキュメントの「ドキュメント » Python 標準ライブラリ » 組み込み型」を参考にしています.リンクのページは日本語で見れますので,こちらも是非.

目次

数値型の種類

 Pythonでは整数を表すint型,浮動小数点数を表すfloat型,複素数を表すcomplex型の3種類の数値型があります.次のようにコンストラクタを使って明示的に型を指定できます.

>>> int(5)
5
>>> float(5)
5.0
>>> complex(5)
(5+0j)
>>> c = complex(3,2)
>>> c.real, c.imag
(3.0, 2.0)

 数値計算の結果は原則int型で,float型があれあfloat型で,complex型があればcomplex型があればcomplex型で返ります.また,Python3からは割り算の結果も原則float型で返ります.

>>> 2+2 # int + int = 0
4
>>> 3 - 4.0 # int - float = float
-1.0
>>> (50 - 5*6) / 4 # (int) / int = float
5.0
>>> 3.2 + 1.8+2j # float + complex = complex
(5+2j) 

数値に対しては数値演算,ビット演算,比較の順に処理される.

数値演算

 数値演算は次のものがあります.表の下のものほど優先順位が高く,先に処理されます.

演算 結果
x + y xとyの和 3 + 2 = 5
x - y xとyの差 3 - 2 = -1
x * y xとyの積 3 * 2 = 6
x / y xとyの商(float) 3 / 2 = 1.5
x // y xとyの商(int) 3 // 2 = 1, 3 // -2 = -2
x % y xとyの剰余 3 % 2 = 1
-x xの符号反転 - 3 = -3
+x xそのもの + 3 = 3
abs(x) xの絶対値 abs(2 - 3) = 1, abs(3+4j) = 5.0
int(x) xの整数変換 int(2.3) = 2
float(x) xの浮動小数点数変換 float(2) = 2.0
complex(re, im) 複素数(re)+(im)j complex(2, 3) = (2+3j)
c.conjugate() 複素数cの共役複素数 (2+3j).conjugate()
divmod(x, y) (x//y, x%y)のペア divmod(2019, 5) = (403, 4)
pow(x, y) xのy乗 pow(2, 3)=8, pow((1+2j), 2) = (-3+4j)
x ** y xのy乗 0 ** 0 = 1

 また,float型をint型に変換する演算には次のものがあります.mathモジュールはインポートが必要です.

演算 結果
round(x[, n]) xをn桁に丸める(偶数丸め) round(1/3, 3) = 0.333, round(3.5) = 4
math.trunc(x) xを整数に切り捨て math.trunc(3.3) = 3, math.trunc(-3.3) = -3
math.floor(x) x以下の最大の整数 math.floor(3.3) = 3, math.floor(-3.3) = -4
math.ceil(x) x以上の最小の整数 math.ceil(3.3) = 4, math.ceil(-3.3) = -3

 さらに,float型の数値が有限の整数値になるかどうかは,is_integerで判定できます.

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

ビット演算

 整数(int型)はビット単位演算ができます.次の演算があります.

演算 結果
x | y 論理和 5|9 = 13 (101|1001=1101)
x ^ y 排他的論理和 5 ^ 9 = 12 (101^1001=1100)
x & y 論理積 5 & 9 = 1 (101&1001=1)
x << n xのnビット左シフト 5 << 2 = 20
x >> n xのnビット右シフト 5 >> 2 = 1
~x xのビット反転 ~5=-6

 さらにビット列への変換やビット長の演算もできます.

>>> n = -37
>>> bin(n) # 2進数表示
'-0b100101'
>>> n.bin_length() # 2進数での長さ
6
>>> bin(n).lstrip('-0b') # 2進数の数字部分
`100101`

バイト列と整数の変換

 to_bytesfrom_bytesを使って整数とバイト列(xFFなど)を変換できる.byteorderの'big',’little’はビッグエンディアン,リトルエンディアンのこと.バイトの並びが前からか後ろからかが異なる.

>>> (1024).to_bytes(2, 'big') # to_bytes(length, byteorder)
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='little', signed=True) # signed=Trueの場合,負の数のみ
b'\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00'
>>> int.from_bytes(b'\x00\x10', 'big')
16
>>> b = (255).to_bytes(3, 'big')
>>> b
b'\x00\x00\xff'
>>> int.from_bytes(b, 'little', signed=True)
-65536

―――以上

参考資料

previous next
IDLEでPython3:基本操作・キーバインド編 IDLEでPython3:シーケンス型編
1
1
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
1