Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
Lusypher Avatar asked Oct 31 '25 20:10

Lusypher


1 Answers

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

like image 131
Ehsan Avatar answered Nov 03 '25 10:11

Ehsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!