Python 在 for 循环中迭代范围的方式是从 (0 到 n) 的范围,它将首先对 0 执行操作,然后对 1、2... 执行操作,直到它在 n 中完成,完成 for 循环。我对么?我有一个工作代码需要针对速度进行优化,它看起来像这样:
Phi = np.arange(0.00005, 0.000101, 0.000001)
Strip_depth = 0.001
for angle in Phi:
Neutral_axis_depth = np.arange(150, 160, 0.0001)
for xn in Neutral_axis_depth:
Sn = int(xn / Strip_depth)
x = [0] # strip center coordinates
for i in range(0, Sn - 1):
x.append(x[i] + Strip_depth)
...
# and the a lot of calculations that will eventually result on C and T
...
comparison_parameter = 0.1
dif = T - C
if comparison_parameter > dif > -comparison_parameter:
# here I need to print the corresponding values of Phi, Xn , C, T and dif in a table
# but that's another question...
我的问题是我需要高精度的结果,为此我必须修改"strip_depth"或"Neutral_axis_depth" np.range step,这将导致更多操作并需要更多时间。我认为,与其按顺序在 Xn 中执行迭代,不如通过在范围内选择一个随机值并根据该值继续执行来节省时间,例如:
如果dif为负,我可以忽略该点之前的范围值 如果dif为正,我可以忽略该点之前的范围值
并在diff > comparison_parameter时重复此操作。这种方式操作不做Sn次,只做几次。另一种选择是确定迭代的值,例如范围的 1/3、范围的 2/3,然后是“剩余范围”的 1/3 或类似的值。在某种程度上,我正在通过这些步骤定义一个新范围。无论哪种方式,我都不知道该怎么做……在此先感谢您的帮助。