python 中的嵌套 while 循环未正确循环

Nested while loop not looping properly in python

我是新手,我对 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...

您正在增加 k 但从未将其重置为 1。所以 k * step 变得越来越大,直到内循环的条件变为假。在这一点上很明显它不再被执行了。

请注意,当您只是在整数范围内迭代时,您应该避免 while 循环。只需使用 for j in range(a, b)。这完全避免了您的代码中存在的那种错误。

如果我没记错的话,您可以将循环替换为:

area = 2*math.pi*R

for j in range(1, R//step + 1):
    # j*step <= R holds
    for k in range(1, area // step + 1):
        # k * step <= area holds here

其中 a // bab 的商。