I am struggling with this particular problem: When I try to simulate the difference equation: $x_{n+2} = 6x_{n+1} - 3x_{n}$ with initial conditions $x_{0} = 1$ and $x_{1} = 3 - \sqrt{6}$, it gives very different answers from it's actual analytical solution $x_{n} = (3 - \sqrt{6})^n$. Can someone please show how I can fix my code in order to resolve this problem?
code:
import numpy as np
from math import sqrt
#simulating numerically over 100 terms
index_seq = []
for i in range(99):
index_seq.append(i)
x = np.zeros(101)
x[0] = 1; x[1] = 3 - sqrt(6)
for n in index_seq:
x[n+2] = 6*x[n+1]-3*x[n]
for x_val in x:
print(x_val)
#simulating analytically over 100 terms
x_a = np.zeros(101)
for n in range(101):
x_a[n] = ((3 - sqrt(6))**n)
for x_val in x_a:
print(x_val)
Your code is fine. From comparing
xandx_aside-by-side, it is highly likely that you observe an example of catastrophic cancellation, which is due to floating point arithmetics in your case.In general, try avoiding subtraction of very small numbers in calculations using programming languages. As an example, you can check that both approaches that are used in the code work fine for a sequence $x_{n+2} = 0.2 x_{n+1} + 0.15x_{n}$ with $x_0 = 1$ and $x_1 = 0.5$, which has an analytical solution $x_n = 2^{-n}$, but doesn't contain subtraction.