简体   繁体   English

多次运行一个函数的循环

[英]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.我有代码来绘制粒子轨迹,直到 3D 矩阵的一部分中的所有空间都被填充。 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.我能够使用 for 循环将一大堆粒子轨迹绘制在一起,并获得填充所有空间所需的数量。 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).我得到粒子数(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).但我想循环多次,然后得到填充矩阵中所有空间(摧毁肿瘤)所需的数字 (n) 的平均值。 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. ''' 但我只从代码的第一部分得到相同的 n 值 10 次。 How do I get it to do the first bit of code new each time and get different n values to average them.我如何让它每次都执行新代码的第一位并获得不同的 n 值来平均它们。

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.计算是在 Path 函数内完成的。 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.如果是这样,您可能需要在每次试验期间使用 random.seed()。 If your simulation is completely deterministic, you should expect the same result every time for the same initial conditions.如果您的模拟是完全确定性的,那么对于相同的初始条件,您应该每次都期望得到相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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