Python 在嵌套循环中查找平均值
我之前想用数组来做这个,但因为我对编程一点都不懂,所以遇到了困难。所以我决定试试别的方法。
我有一个程序:
for x in range (0,N2):
I=1 #resets the variables
Q=0
U=0
for x in range (0,N):
theta= 90+randint (-dtheta,dtheta) #random component
Q0=Q
U0=U
I0=I
I=(I0*cosh(dTp)+S*sinh(dTp))*exp(-dT) #reuses P from previous run through
Q=(Ip*cos(2*theta)+Q0)*exp(-dT)
U=(Ip*sin(2*theta)+U0)*exp(-dT)
P=100*sqrt(Q**2+U**2)/I
print 'x=', x, 'P=', P
这个程序会通过复杂的公式计算出一个P值,并循环执行这些公式N
次。然后它会随机改变一些变量,再重复这个过程N2
次。
我想要做的是:每当它执行N2
次时,计算出那些N
值的平均值。
这是程序当前打印的内容(打印x
和P
):
x=0 P= 0.666656790299
x=1 P= 1.33305129414
x=2 P= 1.99135189726
x=3 P= 2.65356540458
x=4 P= 3.31718464722
x=5 P= 3.94383330744
x=6 P= 4.57470649236
x=7 P= 5.22041300059
x=8 P= 5.87783977662
x=9 P= 6.53297448834
x=0 P= 0.666656790299
x=1 P= 1.33244225853
x=2 P= 1.96631331155
x=3 P= 2.6285933052
x=4 P= 3.2901846442
x=5 P= 3.95565476517
x=6 P= 4.61500717059
x=7 P= 5.27548752021
x=8 P= 5.87881617052
x=9 P= 6.53895040683
这里N2=2
和N=10
。你能看到有两个值大约是0.66(x=0
)吗?还有两个值大约是6.5(x=9
)?我想要能够计算出所有相同N
值的平均数。也就是说,计算所有x=0
的值的平均数(大约是0.66),x=1
的值(大约是1.33),一直到x=9
的值(大约是6.65)。
我的最终目标是把这些平均值和N
画成图。
如果能得到帮助,那就太好了,因为我对编程几乎一无所知。
2 个回答
0
我还是不太明白你在循环中哪里请求计算平均值。
你可以在循环外面放一个计数器变量。用它来记录你计算P的次数。然后再用一个sum_p变量来保存所有计算出来的P值的总和。
这样,平均值就可以用sum_p除以cnt来得到。
当你想开始计算一个新的平均值时,你只需要把cnt和sum_p都设为0。我们可以用N来轻松获得cnt的值。
for x in range (0,N2):
I=1 #resets the variables
Q=0
U=0
sum_p = 0
for x in range (0,N):
theta= 90+randint (-dtheta,dtheta) #random component
Q0=Q
U0=U
I0=I
I=(I0*cosh(dTp)+S*sinh(dTp))*exp(-dT) #reuses P from previous run through
Q=(Ip*cos(2*theta)+Q0)*exp(-dT)
U=(Ip*sin(2*theta)+U0)*exp(-dT)
P=100*sqrt(Q**2+U**2)/I
sum+p += P
print P
print 'Avg', sum_p//N
我不太明白你为什么要创建Q、U、I的重复副本。其实你可以直接在计算中使用之前的副本。这是完全可以的,它会使用旧的值并设置新的值。
I=(I*cosh(dTp)+S*sinh(dTp))*exp(-dT) #reuses P from previous run through
Q=(Ip*cos(2*theta)+Q)*exp(-dT)
U=(Ip*sin(2*theta)+U)*exp(-dT)
2
sums = [0] * N
for x in range (N2):
I = 1 #resets the variables
Q = 0
U = 0
for x in range (N):
theta = 90 + randint(-dtheta, dtheta) #random component
#you don't need to copy these variables, they're redundant
#Q0=Q
#U0=U
#I0=I
#reuse the P-value from previous iteration
I = (I * cosh(dTp) + S * sinh(dTp)) * exp(-dT)
Q = (Ip * cos(2 * theta) + Q) * exp(-dT)
U = (Ip * sin(2 * theta) + U) * exp(-dT)
P = 100 * sqrt(Q**2 + U**2) / I
print P
#add the value of P to the corresponding index at x in sums[]
sums[x] += P
#this is called a list comprehension
#it is a nicer way of looping over an iterable object (like a list)
avgs = [n / float(N2) for n in sums]
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。