2014-11-08 38 views
-1

這是我第一次在這裏問一個問題,所以我希望你能理解我的問題。x減x不是0在R

事情是,我想要做我自己的fft(),而不使用R.中給定的那個。 到目前爲止,它對seq(1,5)這樣的系列效果很好。

但是對於c(1,1)發生了一些奇怪的事情。就我所能指出的而言,似乎x-x在這種情況下不是0。代碼 這裏行:

series <- c(1,1)     # defining the Serie 
     nr_samples <- length(series)  # getting the length 

################# 
# Calculating the harmonic frequncy 
################# 

     harmonic <- seq(0,(nr_samples-1)) 
     harmonic <- 2*pi*harmonic 
     harmonic <- harmonic/nr_samples 

################# 
# Exponential funktion needed for summing up 
################# 

     exponential <- function(index, omega){ 

      result <- exp(-((0+1i)*omega*index)) 

      return(result) 

     } 

################# 
# The sum for calculating the fft 
################# 

     my_fft <- function(time_series, omega){ 

      nr_samples <- length(time_series) 
      summand <- 0 

    # In the next loop the mistakes Happens  
    # While running this loop for harmonic[2] 
    # the rseult should be 0 because 
    # summand = - exp_factor 
    # The result for summand + exp_factor 
    # is 0-1.22464679914735e-16i 

    for (i in 1:nr_samples){ 

      exp_factor <- exponential((i-1), omega)    
      summand <- summand + time_series[i]*exp_factor  
      print(paste("Summand", summand, "Exp", exp_factor)) 
      }              

      return(summand)          
     } 


    transform <- sapply(harmonic, function(x){my_fft(series,x)}) 
    fft_transform <- fft(series) 
    df <- data.frame(transform, fft_transform) 
    print(df) 

誰能告訴我,爲什麼被加數+ exp_factor,諧波[2]是不是零?

回答

3

這通常稱爲FAQ 7.31它說:

,可以精確地R中的數字式表示的唯一的數字是整數和分數,其分母是2。其他數目的功率必須被舍入到(通常)53個二進制數字的準確性。結果,兩個浮點數不可靠地相等,除非它們已經通過相同的算法計算出來,並且不總是那樣。例如

R> a <- sqrt(2) 
R> a * a == 2 
[1] FALSE 
R> a * a - 2 
[1] 4.440892e-16 

函數all.equal()比較了使用。機$ double.eps^0.5的數值公差兩個對象。如果你想要比這更精確的話,你需要仔細考慮錯誤傳播。

欲瞭解更多信息,請參閱David Goldberg(1991),「每位計算機科學家應該知道的關於浮點運算的知識」,ACM Computing Surveys,23/1,5-48,也可通過http://www.validlab.com/goldberg/paper.pdf獲得。

從由Kernighan和Plauger「編程風格的元素」引述如下:

10.0倍0.1是未落1.0。

(報價完)

戈德堡紙是傳說中的,你可能想讀它。這是所有浮點計算的屬性而不是特定於R.

+0

感謝您的回答,認爲這應該有很大的幫助。 – 2014-11-09 11:59:15

相關問題