【问题标题】:How do I make a decaying oscilating function in python?如何在 python 中创建衰减振荡函数?
【发布时间】:2015-08-26 14:04:45
【问题描述】:

我在 python 中有一个代码来表示阻尼振荡器中的能量衰减,它的内容如下:

def E(wt, Q):
    return (np.e**(-x/Q))*(1-(1/2*Q)*np.sin(2*x))
x = np.linspace(0,20,1000)
y0 = E(x,2)
y1 = E(x,4)
y2 = E(x,8)
y3 = E(x,16)
plt.plot(x, y0, 'p', label=r'$Q=2$')
plt.plot(x, y1, 'r', label=r'$Q=4$')
plt.plot(x, y2, 'g', label=r'$Q=8$')
plt.plot(x, y3, 'b', label=r'$Q=16$')
plt.xlabel(r'$wt$')
plt.ylabel(r'$E$')
plt.title (r"$E(t)  -vs.- wt$")
plt.show()

但它应该看起来像这样: https://www.dropbox.com/s/o2mmmi8v6kdnn2v/good_graph.png?dl=0 我究竟做错了什么?我有正确的功能

【问题讨论】:

  • wt 从未在E 的定义中使用
  • 使用 Python 3,您的代码将按原样运行(尽管它可以使用一些改进,正如人们所提到的)。
  • @gregb 他的方程式不正确,尽管您在 python 3 中提出了关于整数除法的有效观点
  • @alexmcf 阅读:“它可以使用一些改进”:)

标签: python numpy matplotlib graph physics


【解决方案1】:

固定方程

def E(wt, Q):
    return np.exp(-x/float(Q)) * ( 1. - (1./2./float(Q))*np.sin(2.* x) )

你的原始方程式

def E(wt, Q):
    return (np.e**(-x/Q))*(1-(1/2*Q)*np.sin(2*x))

错误

  1. 未使用的变量你从不使用wt
  2. BODMAS你没有正确设置衰减参数,所以它会振荡太多。 (1/2*Q) 当你的意思是(1/2/Q)
  3. 整数除法 (仅适用于 Python 您除以整数,这将使您的除法下限。您需要将整数值转换为浮点数,例如(1/2./float(Q))
  4. 颜色参数 您想通过在plt.plot(x, y0, 'p', label=r'$Q=2$') 中传递p 来制作一条紫色线,但p 会创建奇怪的点图行为。要明确地修复颜色名称中的此通道,例如plt.plot(x, y0, color='purple', label=r'$Q=2$')

离题

为了让你的标题更好看:

from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)
plt.title (r"$E(t)$ vs. $w_t$")
plt.xlabel(r'$w_t$')
plt.ylabel(r'$E(t)$')

完整代码

from matplotlib import rc
import bumpy as np
import matplotlib.pyplot as plot

# set up fonts
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)

# set up labels
plt.title (r"$E(t)$ vs. $w_t$")
plt.xlabel(r'$w_t$')
plt.ylabel(r'$E(t)$')

# plot and store plots in yList, zip color labels into loop
yList = []
for i,color in zip(xrange(1,5),['purple', 'r', 'g', 'b']):
    y = E(x, 2**i)
    yList.append(y)
    plt.plot(x, y, color = color, label= r'$Q=%s$' % i)
pt.show()

【讨论】:

    【解决方案2】:

    好像功能不太对劲。我怀疑原始公式是正确的,但您没有在 Python 中正确编码。

    import numpy as np
    import pylab as plt
    def E(x, Q):
        return np.exp(-x/Q) * (1-(1.0/2.0/Q) * np.sin(2*x))
    def main():
        x = np.linspace(0,20,1000)
        y0 = E(x,2)
        y1 = E(x,4)
        y2 = E(x,8)
        y3 = E(x,16)
        plt.plot(x, y0, 'p', label=r'$Q=2$')
        plt.plot(x, y1, 'r', label=r'$Q=4$')
        plt.plot(x, y2, 'g', label=r'$Q=8$')
        plt.plot(x, y3, 'b', label=r'$Q=16$')
        plt.xlabel(r'$wt$')
        plt.ylabel(r'$E$')
        plt.title (r"$E(t)  -vs.- wt$")
        plt.show()    
        return 0
    if __name__ == '__main__':
        main()*
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多