【问题标题】:How to write every nth calculation to an array inside a for loop? (python)如何将每个第 n 个计算写入 for 循环内的数组? (Python)
【发布时间】:2018-10-20 13:12:16
【问题描述】:

我正在 python 中运行一个涉及许多循环的模拟。由于我的笔记本电脑的处理能力有限,我只想将每第 n 个结果写入存储数据的数组。我在网上查看了有关切片数组的信息,但只有在创建了完整大小的数组后才能找到如何进行切片。 for循环如下:

    def Simulate(time, steps):

            history_x = np.zeros(2000000)
            history_y = np.zeros(2000000)

            for i in range(2000000):
                    #calculate positions
                    a_x = ((-6.67e-11)*(mE)/((x**2 + y**2)))
                    a_y = ((-6.67e-11)*(mE)/((x**2 + y**2)))
                    v_x = v_x + (delta_t)*a_x
                    v_y = v_y + (delta_t)*a_y
                    y = y + (delta_t)*v_y + ((delta_t)**2)*a_y*0.5
                    x = x + (delta_t)*v_x + ((delta_t)**2)*(a_x)*0.5

                    rocket_history_x[i] = x
                    rocket_history_y[i] = y

(x,y, v_x, v_y 和 mE 都是在我的代码循环之前定义的,不想弄乱这篇文章)

本质上数学并不重要,但我希望 history_x 和 history_y 只存储 x 和 y 的每第 n 个计算。我该怎么做?

【问题讨论】:

  • rocket_history_x 是从哪里来的?
  • 如果您只存储部分索引,那么 history_x/y 的大小不必为 2000000。只需使用 if 来存储某些索引。
  • 所以你只想为i 的值运行循环,该值可以被n 整除?
  • 2000000之外,假设你想写每10000个值,你可以做if i%10000 == 0,然后保存rocket_history_x.append(x)rocket_history_y.append(y)。在这种情况下,您必须从空列表开始,例如 history_x = []history_y = []

标签: python arrays loops data-storage


【解决方案1】:

根据我上面的评论,完整的代码如下所示。在这里,您初始化两个空列表,而不是创建一个长度为 2000000 的数组。然后,您只需根据 if 条件通过将 append 语句包含在 if 语句中来保存每个第 n 个值。

def Simulate(time, steps):
    history_x, history_y = [[] for _ in range(2)] # initialize lists
    n = 10000
    for i in range(2000000):
        #calculate positions
        a_x = ((-6.67e-11)*(mE)/((x**2 + y**2)))
        a_y = ((-6.67e-11)*(mE)/((x**2 + y**2)))
        v_x = v_x + (delta_t)*a_x
        v_y = v_y + (delta_t)*a_y
        y = y + (delta_t)*v_y + ((delta_t)**2)*a_y*0.5
        x = x + (delta_t)*v_x + ((delta_t)**2)*(a_x)*0.5
        if i% n == 0: # Check for the step
            rocket_history_x.append(x) # store x here
            rocket_history_y.append(y) # store y here

【讨论】:

  • 太棒了,非常感谢 - 刚刚检查过,它有效!
  • 很高兴为您提供帮助:)
【解决方案2】:

您可以进行如下检查:

if i%n == 0:

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 2012-10-21
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多