3
2

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.

R で幾何平均を求めるには...

Last updated at Posted at 2022-05-26

標準の関数がないとお嘆きの方々が,たどり着いたページに

$\displaystyle \sqrt[n]{\prod_{i=1}^{n} x_i}$

に基づいて

prod(x)^(1/length(x))

あるいは,ひどいものだと

max(cumprod(x))^(1/length(x))

なんて書いてあったら,そのまま信じちゃいけない。

以下の実験は,平均値=100,標準偏差=5 の正規乱数を発生させて,幾何平均を求めるもの。

まずは,サンプルサイズ 100 の場合。

いずれも正しい答えを出している。

> set.seed(123)
> n = 10
> x = rnorm(n, 100, 5)
> prod(x)^(1/length(x))
[1] 100.2728276899091
> max(cumprod(x))^(1/length(x))
[1] 100.2728276899091
> exp(mean(log(x)))
[1] 100.272827689909

サンプルサイズ 160 くらいになると,前二者は突然発狂する。

> set.seed(123)
> n = 160
> x = rnorm(n, 100, 5)
> prod(x)^(1/length(x))
[1] Inf
> max(cumprod(x))^(1/length(x))
[1] Inf
> exp(mean(log(x)))
[1] 99.81754279797046

教訓:教科書の定義式をそのままプログラムしてはいけない。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?