Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Why numpy.fft.rfft/irfft transforms do not bring the input back?

I have a list, when I transform it by np.fft.rfft and bring it back by np.fft.irfft it does not work for ex(2) but work with ex(1). What should I do to make it work with ex(2)?

ex(1):

import NumPy as np
z=[[1,2,34,45],[1,2,5,6],[7,8,9,10]]
x1=np.fft.rfft(z)
x2=np.fft.irfft(x1)
print(x2)
print(z)

out:

[[ 1.  2. 34. 45.]
 [ 1.  2.  5.  6.]
 [ 7.  8.  9. 10.]]

[[1, 2, 34, 45], [1, 2, 5, 6], [7, 8, 9, 10]]

ex(2):

import NumPy as np
z1=[[5,8,6],[45,6,3],[847,5847,6]]
x3=np.fft.rfft(z1)
x4=np.fft.irfft(x3)
print(x4)
print(z1)

out:

[[   8.5    10.5 ]
 [  47.25    6.75]
 [2310.25 4389.75]]

[[5, 8, 6], [45, 6, 3], [847, 5847, 6]]

Please help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The isn't an error but the intended behaviour of np.rfft for input of odd length:

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.

This is a consequence of Nyquist-Shannon sampling theorem.

In order to solve this, you can simply add a zero at the end of every rows of z1 if there is an odd number of columns (i.e. zero-padding) by specifying an appropriate n kwarg in np.rfft call which gives:

import numpy as np
z1 = np.array([[5,8,6],[45,6,3],[847,5847,6]])

n = z1.shape[1]
if n%2:
    # zero padding if n odd 
    n += 1
x3 = np.fft.rfft(z1,n,axis=-1)
x4 = np.fft.irfft(x3)

which gives the initial input:

print(x4)
>>>[[5.000e+00 8.000e+00 6.000e+00 0.000e+00]
    [4.500e+01 6.000e+00 3.000e+00 0.000e+00]
    [8.470e+02 5.847e+03 6.000e+00 0.000e+00]]
print(z1)
>>>[[   5    8    6]
    [  45    6    3]
    [ 847 5847    6]]

Feel free to discard the last column of zeros of x4 after going back from the frequency domain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...