Reputation: 29
How can I keep the results of all the iterations for all the quantities I want to compute as an array (row vector) at the end. this is my code.
#import numpy library
import numpy as np
#define the function to compute SHM main quantities for sevral masses
def SHM(k,x,m,v):
for i in range(0,len(m)):
Fx = -k*x
ax = -(k/m[i])*x
w = np.sqrt(k/m[i])
f = w/2*(np.pi)
T = 1/f
Ek = (1/2)*m[i]*v**2
Ep = (1/2)*k*x**2
Et = Ek + Ep
return Fx, ax, w, f, T, Ek, Ep, Et
#Define the values you want to use for calculation
m = [0.2, 0.3, 0.4, 0.5]
k = 200
x = 0.015
v = 0.40
#Call the function
out = SHM(k,x,m,v)
#disaply the results
display(out)
Any help would be appreicted. Thanks.
Upvotes: 0
Views: 41
Reputation: 346
Alternatively to @cnp's answer, you can also store values on every iteration so that you know the state of each variable upon each iteration of m.
#import numpy library
import numpy as np
#define the function to compute SHM main quantities for sevral masses
def SHM(k,x,m,v):
iters = [] #create empty list
for i in range(0,len(m)):
Fx = -k*x
ax = -(k/m[i])*x
w = np.sqrt(k/m[i])
f = w/2*(np.pi)
T = 1/f
Ek = (1/2)*m[i]*v**2
Ep = (1/2)*k*x**2
Et = Ek + Ep
iter = [Fx, ax, w, f, T, Ek, Ep, Et]
iters.append(iter)
return iters
#Define the values you want to use for calculation
m = [0.2, 0.3, 0.4, 0.5]
k = 200
x = 0.015
v = 0.40
#Call the function
out = SHM(k,x,m,v)
#display the results
display(out)
Upvotes: 1
Reputation: 339
For me, it is easy to use python List as below.
#import numpy library
import numpy as np
#define the function to compute SHM main quantities for sevral masses
def SHM(k,x,m,v):
Fx = list()
ax = list()
w = list()
f = list()
T = list()
Ek = list()
Ep = list()
Et = list()
for i in range(0,len(m)):
Fx.append(-k*x)
ax.append(-(k/m[i])*x )
w1 = np.sqrt(k/m[i])
w.append(w1)
f1 = w1/2*(np.pi)
f.append(f1)
T.append(1/f1)
Ek1 =(1/2)*m[i]*v**2
Ek.append(Ek1)
Ep1 = (1/2)*k*x**2
Ep.append(Ep1)
Et.append(Ek1 + Ep1)
return Fx, ax, w, f, T, Ek, Ep, Et
#Define the values you want to use for calculation
m = [0.2, 0.3, 0.4, 0.5]
k = 200
x = 0.015
v = 0.40
#Call the function
out = SHM(k,x,m,v)
#disaply the results
print(out)
output:
([-3.0, -3.0, -3.0, -3.0], [-15.0, -10.0, -7.5, -6.0], [31.622776601683793, 25.819888974716115, 22.360679774997898, 20.0], [49.6729413289805, 40.55778675973612, 35.12407365520363, 31.41592653589793], [0.020131684841794818, 0.024656177762459992, 0.02847050173668708, 0.03183098861837907], [0.016000000000000004, 0.024000000000000004, 0.03200000000000001, 0.04000000000000001], [0.0225, 0.0225, 0.0225, 0.0225], [0.038500000000000006, 0.0465, 0.05450000000000001, 0.0625])
Upvotes: 1