Storing the previous value and reusing it in a loop

Question:

I am implementing a code that after debugging for a month I found out the problem that could be translated in the present simpler case:

for i in range(1,5):
    x=2
    if i==1:
        y=2*x
    else:
        y=2*ypred
    
    ypred=y
    print(i)
    print(ypred)
    
    print(y)

I want to store only the previous value to be reuse in the loop. However, after analysing the print results, I found out that ypred is not the previous value of y in each interaction but exactly the same.

1
4
4
2
8
8
3
16
16
4
32
32

I know this problem may be simple, but I am learning how to code for mathematical purposes.
How do I store only the previous value to be reused in the following interaction?

Thanks in advance.

Asked By: Magnus Moller

||

Answers:

Moving prints in right places leads to this output:

x = 2
ypred = 0
for i in range(1, 5):
    print(f"{i=}")
    print(f"{ypred=}")
    if i == 1:
        y = 2 * x
    else:
        y = 2 * ypred
    print(f"{y=}")
    ypred = y
    print(f"===")

Output:

i=1
ypred=0
y=4
===
i=2
ypred=4
y=8
===
i=3
ypred=8
y=16
===
i=4
ypred=16
y=32
===

Is it desired output?

Answered By: pL3b

Is this what you need?

ypred=0
for i in range(1,5):
    x=2
    if i==1:
        y=2*x
    else:
        y=2*ypred
    
    print(f"i={i} , ypred= {ypred}, y={y}")
    ypred=y

Output:

i=1 , ypred= 0, y=4
i=2 , ypred= 4, y=8
i=3 , ypred= 8, y=16
i=4 , ypred= 16, y=32
Answered By: AziMez
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.