Skip to content

Instantly share code, notes, and snippets.

@taketakeyyy
Last active August 28, 2019 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taketakeyyy/fefe436049b0290f2456ce45236fb5f1 to your computer and use it in GitHub Desktop.
Save taketakeyyy/fefe436049b0290f2456ce45236fb5f1 to your computer and use it in GitHub Desktop.
math.floor()と//演算子の違いというかなんというか
from math import floor
N = 1000000000000000000 # 10**18
# //演算子を使った場合、意図した値になる
a = N//3
print(a)
# 333333333333333333
# floor()を使った場合、意図しない値になる
b = floor(N/3)
print(b)
# 333333333333333312
# N/3 の値を出力すると、有効数字16桁で表現される
c = N/3
print(c)
# 3.333333333333333e+17
# cを f-strings で出力すると、誤差が生じる
print(f"{c:.10f}")
# 333333333333333312.0000000000
# aも f-strings でfloat型に変換するように出力すると、誤差が生じるので注意
print(f"{a:.10f}")
# 333333333333333312.0000000000
# aは f-strings でfloat型に変換しなければ、誤差は生じない
print(f"{a:d}")
# 333333333333333333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment