Tutorial
Tutorial#
We will solve the following problem using a computer using a programming technique called recursion.
Problem
A sequence \(a_1, a_2, a_3, …\) is defined by:
where \(k\) is a constant.
Write down an expression for \(a_2\) in terms of \(k\).
Show that \(a_3 = 4k -21\)
Given that \(\sum_{r=1}^4 a_r = 43\) find the value of \(k\).
We will use a Python to define a function that reproduces the mathematical definition of \(a_k\):
def generate_a(k_value, n):
"""
Uses recursion to return a_n for a given value of k:
a_1 = k
a_n = 2a_{n-1} - 7
"""
if n == 1:
return k_value
return 2 * generate_a(k_value, n - 1) - 7
Attention
This is similar to the mathematical definition the Python definition of the function refers to itself.
We can use this to compute \(a_3\) for \(k=4\):
generate_a(k_value=4, n=3)
-5
We can use this to compute \(a_5\) for \(k=1\):
generate_a(k_value=1, n=5)
-89
Finally it is also possible to pass a symbolic value to k_value
. This allows
us to answer the first question:
import sympy as sym
k = sym.Symbol("k")
generate_a(k_value=k, n=2)
Likewise for \(a_3\):
generate_a(k_value=k, n=3)
For the last question we start by computing the sum:
sum_of_first_four_terms = sum(generate_a(k_value=k, n=r) for r in range(1, 5))
sum_of_first_four_terms
This allows us to create the given equation and solve it:
equation = sym.Eq(sum_of_first_four_terms, 43)
sym.solveset(equation, k)
Important
In this tutorial we have
Defined a function using recursion.
Called this function using both numeric and symbolic values.