0

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?

1
  • 6
    Flip the order of those two assignments. So, assign to x0 first, then assign to x1. Commented Apr 27, 2015 at 0:26

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To update the array in this general problem, the intrinsic functions cshift and eoshift are quite useful.
2

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.