R代码中的奇怪错误:示例时刻

时间:2013-11-05 18:51:58

标签: r

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

1 个答案:

答案 0 :(得分:2)

你的功能是正确计算事物。由于计算在moments函数中执行的方式不同,因此数字的浮点表示形式的误差会有所不同。

基本上发生的事情是因为机器无法准确表示任何给定的浮点数,当您尝试对sqrt(2)这样的数字进行数学运算时,会引入小错误。根据您的操作,这些错误会有所不同。例如,如果您乘以然后相加,则浮点错误可能与您添加然后相乘时不同。在任何情况下,误差都小于称为机器精度的值,大约为1e-16。由于moments与您的函数之间的差异在该值之内,因此差异无意义。

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