【发布时间】:2015-04-20 19:53:56
【问题描述】:
我是新手,我对我的 python 代码有疑问。它没有像我认为的那样执行。 搞砸的部分是嵌套的while:
import math
mu=4*math.pi*10**(-7) ##mu naught
I=
float(input('Enter a value for the current measured in Amperes: '))
R=abs(float(input('Enter a value for the radius
of the circle measured in meters: '))) ##radius
step=R/200 ##Step size for integration
B=[] ##array for B(r)
J=[]
Plot=[B,J]
k = 1 ##step counter for Circumfrence
j = 1 ##step counter for Radius
b_temp = 0 ##place holder to sum b(step*k)
D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
R_Vector = [R-j*step,0]
while(j*step<=R):
while(k*step<=2*math.pi*R):
r=(math.sqrt((R_Vector[0]-D_Vector[0])**2 +
(R_Vector[1]-D_Vector[1])**2))
b_temp = b_temp + (mu/(4*math.pi))*I*step*step/(r**2)
k=k+1
D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
R_Vector = [R-j*step,0]
print(round(r,3), j)
B.append(round(b_temp,8))
print('New j value!')
b_temp=0
J.append(round(step*j,3))
j=j+1
它应该减小半径(第一个 while 循环),然后围绕圆循环,将每块导线的磁场贡献相加。出于某种原因,它并没有像应有的那样在外部循环的每次迭代中循环内部循环,老实说,我不确定为什么。新的 j 值行是让我看看它是否循环正常,这是我的输出:
...
13.657 1
13.884 1
14.107 1
14.327 1
14.543 1
14.756 1
14.965 1
15.17 1
15.372 1
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
...
每个浮点数(半径值)末尾的 1 是 j 值,对于循环周围的每个圆圈,它都保持为 1...
【问题讨论】:
-
我想我应该提到某些行被打断了,因为这些行太长而无法放入编辑框中。所以 I 和 R 输入实际上都是一条线,我想就是这样。
-
期望的输出是什么?
标签: python loops while-loop