1
CalculateSampleMomentAroundZero <- function(x) {
  # Computes the sample moments (up to fourth order) around zero
  #
  # Args:
  #   x: A vector of numbers whose sample moments around zero
  #      will be calculated
  #
  # Returns:
  #   A list that contains the sample moments (up to fourth order)
  #   of the numbers in vector x.

  n <- length(x)
  moment.zero <- lapply(1:4, function(i) (1/n) * sum(x^i))
  names(moment.zero) <- c("first", "second", "third", "fourth")

  moment.zero
}

CalculateSampleMomentAroundMean <- function(x) {
  # Computes the sample moment (up to fourth order) around the mean
  #
  # Args:
  #   x: A vector of numbers whose sample moments around the mean 
  #      will be computed
  #
  # Returns:
  #   A list that contains the sample moments (up to fourth order) 
  #   of the numbers in vector x.

  #
  # Uses the function to calculate sample moments around zero to
  #  obtain the mean (sample moment around zero of first order) of 
  #  the numbers in vector x.
  #
  moments.around.zero <- CalculateSampleMomentAroundZero(x)
  xbar <- moments.around.zero$first

  n <- length(x)
  moment.mean <- lapply(1:4, function(i) (1/n) * sum((x - xbar)^i))
  names(moment.mean) <- c("first", "second", "third", "fourth")

  moment.mean
} 

skewnesskurtosis <- function(x) {
  # Computes the skewness and kurtosis of a vector of numbers
  #
  # Args:
  #   x: A vector of numbers whose skewness and kurtosis will be 
  #      computed.
  #
  # Returns:
  #   A list that contains the skewness and kurtosis of the numbers 
  #   in vector x.

  #
  # Uses the function to compute sample moments around the mean to 
  #  obtain the second, third, and fourth orders of the sample    
  #  moments around the mean.
  #
  moments.around.mean <- CalculateSampleMomentAroundMean(x)
  mu2 <- moments.around.mean$second
  mu3 <- moments.around.mean$third
  mu4 <- moments.around.mean$fourth

  skew <- mu3 / (mu2)^(3/2)
  kurt <- (mu4 / (mu2)^(2)) - 3
  sk <- list(skewness = skew, kurtosis = kurt)

  sk
}

我使用时刻库​​中的函数检查了我的输出,我的第一个函数得到了相同的结果。然而,第二个功能有点奇怪。第二个、第三个和第四个时刻匹配,但第一个不匹配。这很奇怪,因为第一时刻怎么可能是不正确的,而其余的时刻是正确的?我多次查看我的代码,但我仍然找不到错误。有人可以帮忙吗?

编辑:这是我的输入和输出

x <- rnorm(5)

CalculateSampleMomentAroundMean(x)
$first
[1] -2.220446e-17

$second
[1] 0.2923308

$third
[1] -0.02291481

$fourth
[1] 0.1172637

> moment(x, order = 1, central = TRUE)
[1] -8.326673e-18

> moment(x, order = 2, central = TRUE)
[1] 0.2923308

> moment(x, order = 3, central = TRUE)
[1] -0.02291481

> moment(x, order = 4, central = TRUE)
[1] 0.1172637
4

1 回答 1

2

您的功能正在正确计算事物。由于在moments函数中执行的计算方式不同,因此数字的浮点表示形式的误差加起来也不同。

本质上发生的事情是因为机器不能准确地表示任何给定的浮点数,当您尝试对诸如 的数字进行数学运算时sqrt(2),会引入小错误。这些错误加起来会有所不同,具体取决于您在做什么。例如,如果先相乘再相加,浮点误差可能与先相加再相乘不同。在任何情况下,误差都小于称为机器精度的值,大约为 1e-16。由于moments和您的函数之间的差异在该值内,因此差异没有意义。

我建议如果时刻为 1,则自动返回 0。这样可以避免这个问题。

于 2013-11-05T20:13:31.327 回答