Delta函数:DiracDelta函数与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()

任何人都可以解决这个问题?

3

由于错误状态,您不能将单个数字与数组进行比较。

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

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

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(315)
基于python的图书管理系统:图书管理员-木偶-证书验证失败(Faraday::SSLError)
上一篇
麦迪在cba首秀全场录像:在python中模拟nba选秀彩票
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(25条)