LoginSignup
0
0

More than 5 years have passed since last update.

IoTでは知っとかないと python - 数値計算

Last updated at Posted at 2019-04-29

◼️ mathモジュール 数値計算

import math
math.pow(2,16)
65536.0
math.sqrt(100)
10.0
math.log10(100)
2.0
math.sin(180)
-0.8011526357338304
math.trunc(3.14)
3
math.pi
3.141592653589793
math.e
2.718281828459045

◼️ decimalクラス from decimal import Decimal
10進浮動小数点:精度の指定、切り捨てなど規則に厳密さが要求される金額計算などに利用
floatの数値演算では誤差が出る!!

b = float(0.1)+float(0.2)
print(b)
0.30000000000000004

Decimalで見ると・・・デフォルト精度は28桁!

Decimal(float(0.1))
Decimal('0.1000000000000000055511151231257827021181583404541015625')
Decimal(float(0.2))
Decimal('0.200000000000000011102230246251565404236316680908203125')
Decimal(float(0.2)+float(0.1))
Decimal('0.3000000000000000444089209850062616169452667236328125')

こういう時に、decimal.Decimal型は、整数、文字列、タプルから作ることができるため、
以下のようなことができる。

a2 = Decimal('0.1') 文字列から0.1を作成
Decimal(a2)
Decimal('0.1')
b2 = float(0.2)  Floatから0.2を作成
Decimal(b2)
Decimal('0.200000000000000011102230246251565404236316680908203125')

c2 = a2+b2
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'
b2はfloatなので、型違いでエラーとなる。当然、、、

db2 = Decimal(b2)   float型からDecimal型へ変換
c2 = a2+db2
Decimal(c2)
Decimal('0.30000000')
print(c2)
0.30000000

Decimal型を使った計算はfloat型に比べて圧倒的に処理が遅いので、誤差を許さない計算ではない限り、float型を使うことをお勧めします。

◼️ 擬似乱数 randomモジュール

import random
a = random.random() 0.0~1.0間のFLOATを返す!
print(a)
0.020502852686773654

b = random.randint(0,10) 0〜10間のINTを返す!
print(b)
6

c = random.uniform(0,10) 0〜10間のFLOATを返す!
print(c)
9.736606666251387

乱数を再現させたい場合は、「seed(x)」を使えば良い!!
#xは10など適当な定数。省略時は、システムタイムとなる。

c = random.uniform(0,10)
print(c)
5.714025946899135
c = random.uniform(0,10)
print(c)
4.288890546751146
random.seed(10)
c = random.uniform(0,10)
print(c)
5.714025946899135

◼️ 特定分布の乱数生成
nomalvariate(mu,sigma)平均mu 標準偏差sigmaの正規分布
gammavariate(k,theta) 形状母数k,尺度母数thetaのガンマ分布

normal_variate = []
gamma_variate = []

for i in range(1000):
normal_variate.append(random.normalvariate(0,1))
gamma_variate.append(random.gammavariate(3,1))

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