在 MatPlotLib 中绘制降级余弦函数

Plotting a degrading consine function in MatPlotLib

我正在寻找一种创建两个 NumPy 数组的有效方法;第一个是一系列均匀分布的数字,第二个是通过数学函数传递第一个数组数据的结果。

然后将绘制 NumPy 数组,一个作为 x,另一个作为 y。我正在绘制 spring 的阻尼谐波振荡,它作为 x 的函数给出(x 是图中的时间)。该函数是一个指数衰减的正弦波,其中图上的 y 是从零开始的位移:

f(x) = e^(-L.x)。一种 。余弦(w.x)

其中 Law 都是常数(由用户给定),e 是指数。我目前正在这样做,其中 SAMPLE_TIMESAMPLE_RATE 是在别处设置的模块变量。我不想遍历 y 数组,而是在寻找一种一次性完成它的方法。

# numpy arrays for x and y coords
x = np.arange(0, SAMPLE_TIME, SAMPLE_RATE)
y = np.arange(0, SAMPLE_TIME, SAMPLE_RATE)

# iterate over y array
with np.nditer(y, op_flags=['readwrite']) as arr:
    for el in arr:
        # under-damped harmonic oscillator equation
        el[...] = deflection * math.exp(-el*damping_coefficent) * math.cos(w * el)

这是使用 NumPy 的矢量化方法解决问题的示例解决方案,不使用任何 for 循环。我选择了一些示例输入数据来生成结果。我使用 np.cosnp.exp 进行矢量化操作,因为 math.expmath.cos 不允许它们。

SAMPLE_TIME = 100
SAMPLE_RATE = 0.2
x = np.arange(0, SAMPLE_TIME, SAMPLE_RATE)
deflection = 20
damping_coefficent = 0.1
w = 2*np.pi

el = deflection * np.exp(-x*damping_coefficent) * np.cos(w * x)
plt.plot(x, el)
plt.xlabel('x')
plt.ylabel('$f(x)$')

试试这个:

x = np.linspace(0,10,1001)
L = 0.2
a = 2
w = 2
y = np.exp(-L*x) * a * np.cos(w * x)
plt.plot(x,y)
plt.show()

请注意 numpy 数组是向量化的,这意味着您可以对整个数组执行算术运算。

使用numpy数组时,运算会自动矢量化。以下是您可以使用的代码

# Create array x with length 200 and equally spaced values between 0 to 10
x = np.linspace(0,10, 200)    
y = deflection * np.exp(-x * damping_coefficient) * np.cos(w *x)