好き勝手に・げーあにん?

ファミコンと同い年の社会人ヌルオタの日記

プログラマが覚えておくと便利な円周率の桁数

32bit float なら小数点以下8桁、64bit float なら小数点以下15桁まで覚えていれば十分のようだ。

#include <cstdio>

static const float  F_PI   = 3.14159265358979323846264338327950288f;
static const float  F_PI_A = 3.1415926f;
static const float  F_PI_B = 3.14159265f;

static const double PI     = 3.14159265358979323846264338327950288;
static const double PI_A   = 3.14159265358979;
static const double PI_B   = 3.141592653589793;

int main() {

  printf("[float : size %lu]\n", sizeof(float));
  printf("%d = (%.20f == %.20f)\n", F_PI == F_PI_A, F_PI, F_PI_A);
  printf("%d = (%.20f == %.20f)\n", F_PI == F_PI_B, F_PI, F_PI_B);

  printf("[double : size %lu]\n", sizeof(double));
  printf("%d = (%.20f == %.20f)\n", PI == PI_A, PI, PI_A);
  printf("%d = (%.20f == %.20f)\n", PI == PI_B, PI, PI_B);

  return 0;
}

[float : size 4]
0 = (3.14159274101257324219 == 3.14159250259399414062)
1 = (3.14159274101257324219 == 3.14159274101257324219)
[double : size 8]
0 = (3.14159265358979311600 == 3.14159265358979000737)
1 = (3.14159265358979311600 == 3.14159265358979311600)


自分の記憶している範囲(3.1415926535)でも float なら十分だった気がする、と思いつつ、桁を数えたことがなかったので、数えてみたメモでした。あとたった5桁覚えれば double でも十分だったのか。

つか、こんな適当な確認の仕方で大丈夫なんだろうか。