gpt4 book ai didi

Python 在嵌套循环中求平均值

转载 作者:行者123 更新时间:2023-12-01 05:15:26 24 4
gpt4 key购买 nike

我试图使用数组来做到这一点,但我缺乏任何编程技能,这让这变得很困难。所以我们要尝试一些其他的东西。

我有一个程序:

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值,我想要这些值的平均值。

这是程序(打印 xP )当前打印的内容。

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。您看到有两个像 .66 ( x=0 ) 这样的值了吗?还有两个像 6.5 (x=9)?我希望能够获得具有相同 N 值的所有数字的平均值。因此,所有 x=0 值 (~.66)、x=1 值 (~1.33) 一直到 x=9 值 (~6.65) 的平均值。

最终目标是绘制所有这些平均值与 N 的关系图。

任何帮助都会很棒,因为我对编程几乎一无所知。

最佳答案

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]

关于Python 在嵌套循环中求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com