1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのabs()の挙動から学んだこと

Last updated at Posted at 2018-04-27

データ型の情報は、処理の高速化に役立つよ、というお話。

abs()とは

引数の絶対値を返す!!!








・・・だけじゃないんですね。

以下のコードで確認

paiza ioあたりにぶち込んですぐ試せます

abs.py
v = -1.0
print(type(v), abs(v))
# <class 'float'> 1.0

v = 1 - 1j
print(type(v), abs(v))
# <class 'complex'> 1.4142135623730951

つまり?

つまり、
・引数が整数や浮動小数点の場合 → 単に負→正に変えるだけ
・複素数の場合 → 各要素の二乗和の平方根を返す(下のコードの出力値は√2の値になっています)

pythonは動的型付け言語であるため、裏側では
「absを呼び出す前に変数vの型を調べてから」
どの処理を適用するかを決定する必要があります。

このようなオーバーヘッドは、同じ関数を何回も繰り返し呼び出すような場合に無視できない大きさになってしまいます。

そういう場合は?

静的コンパイルを使って高速化しましょう!(雑)

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?