0

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 或类似的值。在某种程度上,我正在通过这些步骤定义一个新范围。无论哪种方式,我都不知道该怎么做……在此先感谢您的帮助。

4

1 回答 1

0

我不完全遵循,但似乎range()不是这个用例的最佳选择。如果要根据需要调整所选值,请使用while+ 手动调整自定义变量:

i = 0 # initiate the custom variable 
while i < Sn - 1: # instead of range()

    # under normal circumstances increase `i` in each loop by 1
    i += 1

    # if specific conditions are met, increase the value as needed
    if dif < 0:
        i += 50 
于 2021-09-04T11:29:15.657 回答