用Python实现Dirac Delta函数

2024-06-17 01:57:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Python 2.7代码中绘制Dirac Delta矩形函数,以便:

enter image description here

from __future__ import division

import numpy as np
import matplotlib.pyplot as plt

def ddf(x,sig):
    if -(1/(2*sig))<=x and x<=(1/(2*sig)):
        val=sig
    else:
        val=0
    return val

X=np.linspace(-5,5,1000)

for sig in np.arange(1,5,0.1):
    plt.cla()
    plt.grid()
    plt.title('Dirac Delta function',size=20)
    plt.xlabel('X values',size=10)
    plt.ylabel("Dirac Delta functions' values",size=10)
    plt.ylim(0,1)
    plt.plot(X,ddf(X,sig),color='black')
    plt.pause(0.5)

plt.show()

但是当我运行代码时,它给出了错误:

Traceback (most recent call last):
  File "c:/Users/Shubhadeep/Desktop/dff.py", line 22, in <module>
    plt.plot(X,ddf(X,sig),color='black')
  File "c:/Users/Shubhadeep/Desktop/dff.py", line 7, in ddf
    if -(1/(2*sig))<=x and x<=(1/(2*sig)):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

谁能解决这个问题


Tags: and代码inimportsizeifasnp
2条回答

问题出在函数中,您正在将listx与floatsig进行比较。一种解决方案是稍微修改函数,使其逐个计算x中的值,然后将计算结果附加到函数将返回的新列表中:

def ddf(x,sig):

   val = []  
   for i in x:
       if -(1/(2*sig))<=i and i<=(1/(2*sig)):
           val.append(sig)
       else:
           val.append(0)
   return val

如错误所述,无法将单个数字与数组进行比较。这里有一个解决方案:

def ddf(x,sig):
    val = np.zeros_like(x)
    val[(-(1/(2*sig))<=x) & (x<=(1/(2*sig)))] = 1
    return val

输出样本:

enter image description here

相关问题 更多 >