Python numpy解包函数 [英] Python numpy unwrap function
问题描述
I am hoping to convert a array of radians into range [0, 2*pi)
and numpy unwrap function is exactly what I need
但是,当我运行以下代码以输入a = [pi, 2*pi, 3*pi]
时:
However, when I run the following code to input a = [pi, 2*pi, 3*pi]
:
import numpy as np
a = np.array([np.pi, 2*np.pi, 3*np.pi])
np.unwrap(a)
我希望结果接近[pi, 0, pi]
.但是,输出仍然是:
I expect the results to be close to [pi, 0, pi]
. However, the output is still:
array([ 3.14159265, 6.28318531, 9.42477796])
它没有展开.但是,如果我改为运行以下命令而不使用numpy.pi
It is not unwrapped. However, if I instead run the following without using the numpy.pi
a = np.array([3.14159265, 6.28318531, 9.42477796])
np.unwrap(a)
输出正确:
array([ 3.14159265e+00, 2.82041412e-09, 3.14159265e+00])
怎么回事?
推荐答案
尽管已接受的答案可以为您提供所需的结果,但我认为这并不是问题的核心,如果我正在解释您的问题正确,是您实际上是要包装您的阶段,而不是包装它.
Although the accepted answer gives you the result you want, I don't think it gets to the heart of the problem which, if I'm interpreting your question correctly, is that you actually want wrap your phase, not unwrap it.
在这种情况下np.unwrap
起作用的原因是对您的数据进行了很小的更改,实际上是np.unwrap
计算其结果的幼稚方式的结果.它只是在数据中查找局部不连续性并进行相应调整.以这种方式获得所需的结果是采样错误的结果.换句话说,如果通过内插得到a = np.array([np.pi, 3*np.pi/2, 2*np.pi, 5*np.pi/2, 3*np.pi])
来改善采样,则调整数据将不再起作用.
The reason np.unwrap
works in this case, with small changes to your data, is actually a consequence of the naive way that np.unwrap
computes its result; it simply looks for local discontinuities in your data and adjusts accordingly. Getting the result you're looking for in this way is a result of sampling errors. In other words, if you improve your sampling by interpolating to get a = np.array([np.pi, 3*np.pi/2, 2*np.pi, 5*np.pi/2, 3*np.pi])
, adjusting the data won't work any more.
更复杂的相位展开方法,例如傅立叶变换方法,即使采样很差,也会使数据无法展开.
A more sophisticated method of phase unwrapping, such as a Fourier transform method, will leave your data unwrapped, even if the sampling is poor.
如果您确实想将数据限制为[0, 2*pi)
,则np.unwrap
是所需内容的逆.我可以想到的最简单的包装相位的方法是使用模运算符:
If you really want to constrain your data to [0, 2*pi)
, np.unwrap
is the inverse of what you want. The simplest way I can think of to wrap your phase is with the modulo operator:
import numpy as np
a = np.array([np.pi, 2 * np.pi, 3 * np.pi])
a_wrapped = a % (2 * np.pi)
print (a_wrapped)
当然,由于采样错误,np.unwrap(a_wrapped)
不会返回原始的a
,因此可能不清楚这是相反的.但是,如果您改进采样,则确实会返回原始的a
:
Of course, because of the sampling errors, np.unwrap(a_wrapped)
does not return your original a
, so it may not be clear that this is the inverse. However, if you improve your sampling, it does indeed return the original a
:
import numpy as np
a = np.arange(0, 4 * np.pi, np.pi/10)
print (a)
a_wrapped = a % (2 * np.pi)
print (a_wrapped)
a = np.unwrap(a_wrapped)
print (a)
这篇关于Python numpy解包函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!