x减去x在R中不是0

x减去x在R中不是0,r,fft,difference,complex-numbers,R,Fft,Difference,Complex Numbers,这是我第一次在这里提问,所以我希望你能理解我的问题 问题是,我想做我自己的fft(),而不使用R中给定的fft。 到目前为止,它对于像seq(1,5)这样的系列非常有效 但是对于c(1,1),发生了一些奇怪的事情。据我所知,在这种情况下,x-x似乎不是0。 下面是代码行: series <- c(1,1) # defining the Serie nr_samples <- length(series) # gett

这是我第一次在这里提问,所以我希望你能理解我的问题

问题是,我想做我自己的fft(),而不使用R中给定的fft。 到目前为止,它对于像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)

系列这通常指的是:

在R的数字类型中,唯一可以精确表示的数字是分母为2的幂的整数和分数。其他数字必须四舍五入到(通常)53位二进制数字的精度。因此,两个浮点数将不会可靠地相等,除非它们是通过相同的算法计算的,并且不总是偶数。比如说

R>a*a==2
[1] 假的
R> a*a-2
[1] 4.440892e-16
函数all.equal()使用.Machine$double.eps^0.5的数字公差比较两个对象。如果你想要比这更准确的话,你就需要仔细考虑错误传播。 如需更多信息,请参阅David Goldberg(1991),“每位计算机科学家对浮点运算的了解”,ACM Computing Surveys,23/1,5-48,也可通过访问获取

引用Kernighan和Plauger的“编程风格元素”:

10.0乘以0.1几乎从来都不是1.0

(报价结束)


戈德堡报纸是传奇,你可能想读它。这是所有浮点计算的一个属性,不是特定于R的。

谢谢你的回答,我认为这会很有帮助。
R> a <- sqrt(2)
R> a * a == 2
[1] FALSE
R> a * a - 2
[1] 4.440892e-16