Lusypher
Lusypher

Reputation: 53

Dirac Delta function with Python

I tried to plot the Dirac Delta rectangular function in Python 2.7 code such that:

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()

But when I ran the code it gave the error:

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()

Can anyone solve this?

Upvotes: 4

Views: 27838

Answers (2)

Ehsan
Ehsan

Reputation: 12397

As the error states, you cannot compare single number to an array. Here is a solution for it:

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

output sample:

enter image description here

Upvotes: 3

iffanh
iffanh

Reputation: 96

The problem is in the function, you are comparing list x to a float sig. One solution would be to slightly modify the function such that it evaluates the values in x one-by-one, and then append the evaluation in a new list that will be returned by the function:

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

Upvotes: 2

Related Questions