HEMS - 2 months ago 5x

Python Question

I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?

`import numpy as np`

import matplotlib.pyplot as plt

# omega =2*pi

x=np.linspace(0,2*np.pi,2000)

y1=np.sin(1*2*np.pi*x)/1

y2=np.sin(3*2*np.pi*x)/3

y3=np.sin(5*2*np.pi*x)/5

y4=np.sin(7*2*np.pi*x)/7

y5=np.sin(9*2*np.pi*x)/9

Y=y1+y2+y3+y4+y5

plt.plot(x,Y)

plt.grid()

plt.show()

#Implementation in for loop is not working

def Harmonic(i):

y = []

for n in range(0,i):

y=np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1)

y += y

plt.plot(x,y)

plt.grid()

plt.show()

Answer

Do you mean something like that?

```
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,2*np.pi,2000)
y = [0 for _ in x]
def Harmonic(i):
global y
global x
for n in range(0,i):
y += np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1)
Harmonic(5)
plt.plot(x,y)
plt.grid()
plt.show()
```

Or, if you want to have the function the make the plot:

```
import numpy as np
import matplotlib.pyplot as plt
def Harmonic(i):
x=np.linspace(0,2*np.pi,2000)
y = [0 for _ in x]
for n in range(0,i):
y += np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1)
plt.plot(x,y)
plt.grid()
plt.show()
Harmonic(5)
```

Source (Stackoverflow)

Comments