简体   繁体   中英

Running a loop of a function multiple times

I have code to plot particle trajectories until all the spaces in a portion of a 3D matrix are filled. This is based on the final position of the particle. A simplified simulation of particles in a beam of radiation traveling through a body.

I was able to use a for loop to plot a whole bunch of particle trajectories together, and to get the number it takes to fill up all the spaces. I did this by, '''

n = 100
for n in range(particles):
    Path(ax,body)
    if body==[[[0 for k in range(10)] for j in range(10)] for i in range(10)]:
        print('Tumor destroyed after particle number', n)
        break
plt.show()

'''

and I get the number of particles (n). But I want to loop this many times and then get an average of the number (n) it takes to fill all the spaces in the matrix (destroy the tumor). I tried doing '''

trials=10
for i in range(trials): 
    for n in range(particles):
        Path(ax,body)
        if body==[[[0 for k in range(10)] for j in range(10)] for i in range(10)]:
            print('Tumor destroyed after particle number', n)
            break

''' but i just get the same n value from the first part of code 10 times. How do I get it to do the first bit of code new each time and get different n values to average them.

EDIT The numbers should all be different since I am using random numbers for the calculations. The calculations are being done inside the Path function. I just want to runt the first snipet of code multiple times and am not sure how to execute it. I can add the full code, but it is very long.

Does your simulation use some randomized initial conditions? If so, you probably need to use random.seed() during each trial. If your simulation is completely deterministic, you should expect the same result every time for the same initial conditions.

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