除算の商と余りを求める

"//"は商を切り捨てます。divmod()を用いると商と余りのタプルを得られます。
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
>>> 10 % 3
1
>>> 10 % -3
-2
>>> -10 % 3
2
>>> divmod(10,3)
(3, 1)
>>> divmod(10,-3)
(-4, -2)

絶対値を求める

>>> abs(10)
10
>>> abs(-10)
10

小数点を切り上げ・切り捨て・四捨五入する

math.ceil()で切り上げ、math.floor()で切り捨て、round()で四捨五入を行います。round()には四捨五入の桁数を指定することができます。
>>> import math
>>> f = 3.4
>>> math.ceil(f)
4
>>> math.floor(f)
3
>>> round(f)
3
>>> f = 3.5
>>> round(f)
4
>>> f = 1.258
>>> round(f,2)
1.26

三角関数を計算する

>>> import math
>>> math.sin(math.pi/2)
1.0
>>> math.cos(0.0)
1.0
>>> math.tan(0.0)
0.0

対数を計算する

>>> import math
>>> math.log(math.e)
1.0
>>> math.log10(10.0)
1.0

平方根を計算する

>>> import math
>>> math.sqrt(4.0)
2.0
>>> math.sqrt(2.0)
1.4142135623730951

乗数を計算する

>>> pow(2.0,3.0)
8.0
>>> 2.0 ** 3.0
8.0

10進浮動小数点数を用いて計算する

>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1428571428571428571428571429')

10進浮動小数点数の計算で精度を指定する

>>> import decimal
>>> decimal.getcontext().prec = 6
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.142857')
>>> decimal.getcontext().prec = 25
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1428571428571428571428571')

複素数を扱う

>>> complex(1.5,3.0)
(1.5+3j)
>>> c = complex(1.0,2.0)
>>> c.real
1.0
>>> c.imag
2.0
>>> c.conjugate()
(1-2j)
>>> c + c.conjugate()
(2+0j)
>>> c * c.conjugate()
(5+0j)

乱数を生成する

random.random()で0.0以上1.0未満の乱数を得られます。random.seed()で乱数の種を固定することができます。
>>> import random
>>> random.random()
0.12479568149772347
>>> random.seed(100)
>>> random.random()
0.14566925510413031

一様分布や正規分布などの分布もあります。
>>> import random
>>> random.uniform(0.0,5.0)
2.9041025892999208
>>> random.gauss(0.0,1.0)
-1.9946445317423875

整数と浮動小数点を相互変換する

>>> i = 1
>>> float(i)
1.0
>>> f = 4.2
>>> int(f)
4
>>> f = 4.5
>>> int(f)
4
>>> f = -4.6
>>> int(f)
-4




タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2009年08月01日 13:20