简体   繁体   中英

Python double loop? While and for loop?

I want to loop over a range of c values? How do I do that? I tried having a for loop or a while loop on the outside:

Note: I want c between 4 to 15 with 120 values

for c in range(4,15):
    i=0
    while i< nt-1: #if i<nt-1 is true, the body below will be excuted
        #Update the acceleration using the following equation
        x[i+1] = (-y[i]-z[i])*deltat+x[i]
        #Update the velocity using the follwing equation
        y[i+1] =(x[i]+a*y[i])*deltat+y[i]
        #Update the displacement, using follwing equation
        z[i+1] = (b+z[i]*(x[i]-c))*deltat+z[i]
        #go to next time step
        i=i+1

OR

c=arange(4,15,1)
for p in c:
   while i< nt-1: #if i<nt-1 is true, the body below will be excuted
        #Update the acceleration using the following equation
        x[i+1] = (-y[i]-z[i])*deltat+x[i]
        #Update the velocity using the follwing equation
        y[i+1] =(x[i]+a*y[i])*deltat+y[i]
        #Update the displacement, using follwing equation
        z[i+1] = (b+z[i]*(x[i]-p))*deltat+z[i]
        #go to next time step
        i=i+1

Since you're already using NumPy, the following is probably the most natural:

for c in np.linspace(4, 15, 120):
   ...

The linspace() call produces 120 values:

In [33]: np.linspace(4, 15, 120)
Out[33]: 
array([  4.        ,   4.09243697,   4.18487395,   4.27731092,
         4.3697479 ,   4.46218487,   4.55462185,   4.64705882,
         4.7394958 ,   4.83193277,   4.92436975,   5.01680672,
        ...
        14.35294118,  14.44537815,  14.53781513,  14.6302521 ,
        14.72268908,  14.81512605,  14.90756303,  15.        ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM