1
0

More than 1 year has passed since last update.

[AtCoder]pythonで整数のべき乗の計算にmath.powは使わない(pow() or **を使う)

Last updated at Posted at 2022-04-09

結論

べき乗の計算時はpow or ** を使おう

math.powの仕様

公式ドキュメントより引用する

math.pow(x, y)
x の y 乗を返します。例外的な場合については、 C99 標準の付録 'F' に可能な限り従います。特に、 pow(1.0, x) と pow(x, 0.0) は、たとえ x が零や NaN でも、常に 1.0 を返します。もし x と y の両方が有限の値で、 x が負、 y が整数でない場合、 pow(x, y) は未定義で、 ValueError を送出します。
組み込みの ** 演算子と違って、 math.pow() は両方の引数を float 型に変換します。正確な整数の冪乗を計算するには ** もしくは組み込みの pow() 関数を使ってください

math.pow()は両方の引数をfloatに変換して計算するため、正しくない
※math.pow()の返り値はfloatであることから、floatに変換していることがわかります。

整数の場合

下記で結果を確認します。

import math

def calc_pow(a, b):
    print("pow:{}".format(pow(a, b)))
    print("** :{}".format(a**b))
    print("math.pow:{}".format(math.pow(a, b)))
    print("int(math.pow):{}".format(int(math.pow(a, b))))
    return
if __name__ == "__main__":
    calc_pow(3, 115)

結果

pow          :7395104114874202511988394360121831439224179537192802907
**           :7395104114874202511988394360121831439224179537192802907
math.pow     :7.395104114874203e+54
int(math.pow):7395104114874203067169776178544793179075482331828453376

小数点の場合

# 関数は同じため省略
    calc_pow(0.123, 0.456744)
    calc_pow(11000.555, 0.0001)

結果

pow:     0.38398973983417967
** :     0.38398973983417967
math.pow:0.38398973983417967
int(math.pow):0
pow:     1.0009310032151988
** :     1.0009310032151988
math.pow:1.0009310032151988
int(math.pow):1

小数点ではpow or ** とmath.powは同じ結果であった。
そのためpow or **を使用したほうがよい

pow と ** の違い

下記に詳しい記事がありましたので、ご参照ください
https://qiita.com/R_olldIce/items/ab3f382643e92122f8ef

参考資料

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