Raphael Hatami
Raphael Hatami

Reputation: 53

using for loops in python for integration?

I have a simple code that works for single values of n, but I need to set up a loop to calculate/plot for n=2,5,20. I'm new to python, can someone show me how to do this?

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
import math as m
y = lambda t: 3*t
T = 4      #period
n=20
#n = np.array([2,5,20])
w = 2*np.pi*n/T

#Bn
def integrand(t):
    return y(t)*np.sin(n*w*t)
Bn= (2/T)*quad(integrand,-T/2,T/2)[0] 
#An
def integrand(t):
    return y(t)*np.cos(n*w*t)
An= (2/T)*quad(integrand,-T/2,T/2)[0]

#A0
def integrand(t):
    return y(t)
A0= (1/T)*quad(integrand,-T/2,T/2)[0]

print(Bn,An,A0)
y = lambda t: A0+An*np.cos(n*w*t)+Bn*np.sin(n*w*t)

#y = lambda t: ((-1)**(n+1))*Bn*np.sin(w*n*t)

t = np.linspace(-6, 6)    
plt.plot(t,y(t))

Upvotes: 0

Views: 670

Answers (1)

ferhen
ferhen

Reputation: 653

You can use a for loop and do something like this:

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
import math as m

y = lambda t: 3*t
T = 4      #period
n_list = np.array([2,5,20])

for n in n_list:
    w = 2*np.pi*n/T
    Bn = (2/T)*quad(lambda t: y(t)*np.sin(n*w*t), -T/2, T/2)[0] 
    An = (2/T)*quad(lambda t: y(t)*np.cos(n*w*t), -T/2, T/2)[0]
    A0 = (1/T)*quad(lambda t: y(t), -T/2, T/2)[0]

    print(Bn,An,A0)
    y = lambda t: A0+An*np.cos(n*w*t)+Bn*np.sin(n*w*t)

    #y = lambda t: ((-1)**(n+1))*Bn*np.sin(w*n*t)

    t = np.linspace(-6, 6)
    plt.plot(t,y(t))
    plt.show()

Upvotes: 1

Related Questions