Reputation: 45
I'm working on Fortran 90. I need to calculate a recursion like xn = 6*(xn-1) + 7*(xn-2) where (xn-1) is the n-1 step and (xn-2) is the n-2 step. So if we set x1 = 2 and x0 = 1 we get x2 = 6*x1 + 7*x0 and so on for each n.
So I wrote
x0 = 1.
x1 = 2.
do i = 1,20
xn = 6.*x1 + 7.*x0
x1 = xn
x0 = x1
end do
but this code is replacing x0 and x1 for xn and I need to replace x1 for xn and x0 for x1 in each step. I'd tryed many things but I failed. Any idea how to do that?
Upvotes: 0
Views: 907
Reputation: 5450
Though the answer has already been added to this question, let me answer a more general question which is encountered more frequently. Consider the problem where the very next value in the iteration depends on n
previous values. In the present case n = 2
. The general strategy to solve this problem is to construct another 1-d array of size n
and save all the initial values x(1),x(2),..,x(n)
in this array. Then in each iteration we use these values to calculate the next value x(n+1)
and update the array with x(1) by x(2), x(2) by x(3),...,x(n) by x(n+1)
and again use these values to calculate the next value of x
and so on. A particular example where such strategy must necessarily be used is the integration of time-delayed systems.
Upvotes: 3
Reputation: 8140
@parthian-shot has given the correct answer in the comment. But that leaves the question marked as unanswered, so I am repeating it here:
You are assigning the value of xn
to x1
, and then the value of x1
(which is now the same as xn
) to x0
. You just need to flip it around:
do i = 1,20
xn = 6.*x1 + 7.*x0
x0 = x1
x1 = xn
end do
Upvotes: 2