为什么 numpy.fft.rfft/irfft 转换不带回输入?
Why numpy.fft.rfft/irfft transforms do not bring the input back?
我有一个列表,当我通过 np.fft.rfft 转换它并通过 np.fft.irfft 将其带回时,它不适用于 ex(2) 但适用于 ex(1)。我应该怎么做才能让它与 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)
输出:
[[ 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)
输出:
[[ 8.5 10.5 ]
[ 47.25 6.75]
[2310.25 4389.75]]
[[5, 8, 6], [45, 6, 3], [847, 5847, 6]]
请帮忙。
这不是错误,而是 np.rfft 对于奇数长度输入的预期行为:
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.
这是 Nyquist-Shannon sampling theorem 的结果。
为了解决这个问题,如果列数为奇数(即 z1
,您可以在每行末尾添加一个零=13=]) 通过在 np.rfft
调用中指定适当的 n
kwarg 给出:
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)
给出初始输入:
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]]
从频域返回后,随意丢弃 x4
的最后一列零。
我有一个列表,当我通过 np.fft.rfft 转换它并通过 np.fft.irfft 将其带回时,它不适用于 ex(2) 但适用于 ex(1)。我应该怎么做才能让它与 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)
输出:
[[ 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)
输出:
[[ 8.5 10.5 ]
[ 47.25 6.75]
[2310.25 4389.75]]
[[5, 8, 6], [45, 6, 3], [847, 5847, 6]]
请帮忙。
这不是错误,而是 np.rfft 对于奇数长度输入的预期行为:
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.
这是 Nyquist-Shannon sampling theorem 的结果。
为了解决这个问题,如果列数为奇数(即 z1
,您可以在每行末尾添加一个零=13=]) 通过在 np.rfft
调用中指定适当的 n
kwarg 给出:
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)
给出初始输入:
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]]
从频域返回后,随意丢弃 x4
的最后一列零。