LoginSignup
0
4

More than 1 year has passed since last update.

~ 基本演算 ~ チートシート

Last updated at Posted at 2021-03-23

目次

べき乗 pow(x,n,MOD)
実数を整数にする
 丸め処理(四捨五入) round()
 切り捨て math.floor()
 切り上げ math.ceil()

四則演算 + - * / 商// 余り% べき乗**
最小値_最大値 min() max()
平方根 math.sqrt()

はじめに

チートシートの扱いついてはここを読んでください

べき乗

calculation.py
print(pow(2,10))
出力
>>> 1024

pow(x,n)x**nと同じ

calculation.py
print(pow(2,1024,1000000007))
出力
>>> 812734592

第三引数にMODを入れると、MODで割った余りを出力する
pow()繰り返し二乗法を用いて実装されているので、乗数が大きくなったりしても早く計算できる

平方根

calculation.py
import math
print(math.sqrt(144))
出力
>>> 12

pow()とか**で求めてもよいが、pow()が1番早い(らしい)
まあそこまで大きな時間差にもならないだろうし、正直どれ良さそう(import mathするのめんどくさいし)

実数を整数にする

丸め処理(四捨五入)

calculation.py
print(round(114514.1919))
出力
>>> 114514

厳密には四捨五入ではないが、ほぼ四捨五入みたいなもん

calculation.py
print(round(114514.1919, 2))
print(round(114514.1919, 1))
print(round(114514.1919, 0))

print(round(1145141919, 0))
print(round(1145141919, -1))
print(round(1145141919, -2))
出力
>>> 114514.19
>>> 114514.2
>>> 114514.0

>>> 1145141919
>>> 1145141920
>>> 1145141900

四捨五入する位の位置を指定すると有効数字を変えられる

切り捨て

calculation.py
import math
print(math.floor(114514.1919))
出力
>>> 114514

floor : 英語で「床」

calculation.py
print(int(114514.1919))
出力
>>> 114514

int()も切り捨てなので代用可能

calculation.py
print(33/4)
print(33//4)
出力
>>> 8.25
>>> 8

int同士を割り算した結果を切り捨てたいなら、商を求める//を使えばいい
math.floor()よりこっちのほうが早いらしい

切り上げ

calculation.py
import math
print(math.ceil(114514.1919))
出力
>>> 114515

ceil : 英語で「天井」

calculation.py
print(33/4)
print(-(-33//4))
出力
>>> 8.25
>>> 9

int同士を割り算した結果を切り上げたいなら、これも商を求める//を使えばいい(これ思いついた人賢い)

四則演算

calculation.py
print(33 + 4)
print(33 - 4)
print(33 * 4)
print(33 / 4)
出力
>>> 37
>>> 29
>>> 132
>>> 8.25

Hello, world!の次にやった気がするし、まあ...

calculation.py
print(33 / 4)
print(33 // 4)
print(33 % 4)
出力
>>> 8.25
>>> 8
>>> 1

商と余りも出せる

calculation.py
print(-33 // 4)
print(-33 % 4)
出力
>>> -9
>>> 3

商が負になる場合は、余りが正になるように計算される

calculation.py
print(2**10)
出力
>>> 1024

べき乗も計算可能

最小値_最大値

calculation.py
print(min(114,514,810))
print(max(114,514,810))
出力
>>> 114
>>> 810

3つ以上でもOK

0
4
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
4