Programming a recursive sequence with PARI/GP

391 Views Asked by At

My question is: how to program a recursive sequence with PARI/GP software? For example the sequence: $$x_{n+1}=x_{n}-1, x_0=10.$$ Thank you.

3

There are 3 best solutions below

0
On BEST ANSWER

There are a few ways, with minor variations. Here is one good way:

x(n) = if(n<0, 0, n==0, 10, x(n-1)-1);

which gives the expected result of $\, x(n) = 10-n \,$ if $\, n\ge 0.$ It also gives $\, x(n) = 0 \,$ if $\, n<0. $ You can change that behavior to raise an error for invalid input. You can extend the recursion range:

x(n) = if(n<0, x(n+1)+1, n==0, 10, x(n-1)-1);

If the recursion is computationally expensive, you may want to use Memoization which would require some changes in the code to save previous results.

1
On

The given recurrence relation can be programmed as follows :

x(n)={if(n>0,h=x(n-1)-1);if(n==0,h=10);h}
1
On

If only some special value is needed, say $x_N$, $N=100$, then

{x(N) = local(a); a = 10; for(k=1, N, a=a-1); a}

Then for instance:

? for( n=0, 11, print( "x(", n, ") = ", x(n) ) ) 
x(0) = 10
x(1) = 9
x(2) = 8
x(3) = 7
x(4) = 6
x(5) = 5
x(6) = 4
x(7) = 3
x(8) = 2
x(9) = 1
x(10) = 0
x(11) = -1

(The locale can be removed safely, if a is not used around.) If we need all terms, then it is better to store the data in a list. Please mention if this is the case.