'How to save vector so it can be accessed further down the program?

I've been struggling trying to find a way I can store a vector so I can use it later. Here's my code:

while cota > RTOL:
    for i in range (0, n + 1):
        if i == 0:
            u[i] = T_b - T_inf
        elif 0 < i < n:
            u[i] = (u[i + 1] + u[i - 1])/y
        else:
            u[i] = 0

The vector "u" changes with each iteration as the resulting vector from an iteration is the input for the next, however, in order to define the cut-off for the loop I need to be able to access both the current and previous iteration (the cut-off happens once a certain tolerance is reached and that requires being able to compare the current iteration to the previous one). In order to do this I've tried writing it onto a text file, but I'm wondering if there's a more elegant solution that somehow allows me to avoid that.



Solution 1:[1]

I recommend you remove the conditional from the loop, and invent a new vector v to store results.

while cota > RTOL:
    v = {}  # Or a numpy array? Unclear from your example.
    v[0] = T_b - T_inf
    v[n] = 0
    for i in range(1, n):
        v[i] = (u[i + 1] + u[i - 1]) / y

Then do something useful with v, not sure what your use case is. Perhaps you want to copy it on top of u for subsequent processing.

By using two separate vectors you won't have to worry about u[i - 1] giving a value you munged just a moment ago on the previous loop iteration.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J_H