0
0

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 1 year has passed since last update.

pythonでハマりがちな誤差(随時加筆)

Posted at

(随時加筆)

pythonで生じがちな誤差の根本原因は私の遭遇した限り以下の通り

  • float型の精度の限界
    • 15,16桁付近から誤差が生じる

log

ある数の桁数を求めるとき、その方法のひとつとしてlog10を適応した整数部分により求める方法がある。
このとき、ある数の桁数が大きいと誤差が生じるので注意。

Anti-pattern
int(math.log10(int('9'*14)))
>> 13
int(math.log10(int('9'*15)))
>> 15
Recommended
len(str(int('9'*14)))-1
>> 13
len(str(int('9'*15)))-1
>> 14

割り算

pythonでは割り算の演算として / と // がある。
/は割り切れるか否かに限らずfloat型に変換した演算を行う。
//は整数としての演算を行う。
このため、桁数が大きい整数の割り算の場合、//で計算した方が精度が担保される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?