numpy.fft.irfft: 为什么需要 len(a)?

numpy.fft.irfft: Why is len(a) necessary?

documentation for numpy.fft.irfft, the inverse discrete Fourier transform for real input, 状态

This function computes the inverse of the one-dimensional n-point discrete Fourier Transform of real input computed by rfft. In other words, irfft(rfft(a), len(a)) == a to within numerical accuracy. (See Notes below for why len(a) is necessary here.)

但是,注释部分似乎没有说明为什么在这种情况下需要指定 len(a)。事实上,即使省略长度,一切似乎都能正常工作:

numpy.random.seed(123456)
a = numpy.random.rand(20)
# array([0.12696983, 0.96671784, 0.26047601, 0.89723652, 0.37674972,
#        0.33622174, 0.45137647, 0.84025508, 0.12310214, 0.5430262 ,
#        0.37301223, 0.44799682, 0.12944068, 0.85987871, 0.82038836,
#        0.35205354, 0.2288873 , 0.77678375, 0.59478359, 0.13755356])
numpy.fft.irfft(numpy.fft.rfft(a))
# array([0.12696983, 0.96671784, 0.26047601, 0.89723652, 0.37674972,
#        0.33622174, 0.45137647, 0.84025508, 0.12310214, 0.5430262 ,
#        0.37301223, 0.44799682, 0.12944068, 0.85987871, 0.82038836,
#        0.35205354, 0.2288873 , 0.77678375, 0.59478359, 0.13755356])

我可以在调用 numpy.fft.rfft 时省略 len(a) 吗?

如评论中所述,如果长度为偶数,则省略长度有效,但如果长度为奇数则无效:

numpy.random.seed(123456)
a = numpy.random.rand(21)
# array([0.12696983, 0.96671784, 0.26047601, 0.89723652, 0.37674972,
#        0.33622174, 0.45137647, 0.84025508, 0.12310214, 0.5430262 ,
#        0.37301223, 0.44799682, 0.12944068, 0.85987871, 0.82038836,
#        0.35205354, 0.2288873 , 0.77678375, 0.59478359, 0.13755356,
#        0.85289978])
numpy.fft.irfft(numpy.fft.rfft(a))
# array([0.24111601, 0.90078174, 0.37803686, 0.86982605, 0.38581891,
#        0.29202917, 0.72002065, 0.59446031, 0.23485829, 0.55698438,
#        0.42253411, 0.26457788, 0.49961714, 1.06138356, 0.45849842,
#        0.22863701, 0.68431715, 0.73579194, 0.14511054, 0.82140976])

numpy.fft.rfft and numpy.fft.irfft 的 return 值的文档解释了为什么会发生这种情况,尽管对 numpy.fft.irfft 的“注释”部分的引用仍然具有误导性:

numpy.fft.rfft(a, n=None, axis=-1, norm=None)

Returns:

out : complex ndarray
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. If n is even, the length of the transformed axis is (n/2)+1. If n is odd, the length is (n+1)/2.


numpy.fft.irfft(a, n=None, axis=-1, norm=None)

Returns:

out : ndarray
The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified. The length of the transformed axis is n, or, if n is not given, 2*(m-1) where m is the length of the transformed axis of the input. To get an odd number of output points, n must be specified.