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.

浮動小数点数の誤差は怖いよって話

Last updated at Posted at 2024-07-04

はじめに

コンピュータで浮動小数点数を用いて演算した場合,ちょくちょく誤差が発生することがある.

たとえば,2.104136という数字を1000000回足した場合と,2.104136に1000000を掛けた場合では,演算結果が異なる.

どれくらい結果に違いが出るのか,見てみましょう.

ちょっとプログラムを書いて試してみます

# 2.104136を1000000回足す
sum = 0.0
for i in range(1000000):
    sum += 2.104136

# 2.104136に1000000を掛ける
product = 2.104136 * 1000000

# 結果を表示(小数第10位まで)
print("2.104136を1000000回足した結果: {:.10f}".format(sum))
print("2.104136に1000000を掛けた結果: {:.10f}".format(product))

実行結果

実行したらこんな感じでした.
"2.104136を1000000回足した結果"と"2.104136に1000000を掛けた結果"では,0.0000318480も差分が出てしまうということですね.怖いですね!

C:\test>python fudo_test.py
2.104136を1000000回足した結果: 2104135.9999681520
2.104136に1000000を掛けた結果: 2104136.0000000000
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?