Finding periodic points with Python

Let's suppose that I want to find a point of period 3 for the function $f(x) = x^3-3x-1$. Looking at graphs of $y=x$, $y=f(x)$, and $y=f^3(x)$, I notice that there might be such a point just a little to the right of $x=-0.5$. Let's try to find it!

In [1]:
# Load some libraries.
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from scipy.optimize import brentq
In [2]:
# Examine the graph
def f(x): return x**3 - 3*x - 1
def F(x): return f(f(f(x)))
xs = np.linspace(-1,1,1000)
ys = f(xs)
Ys = F(xs)
plt.plot(xs,xs)
plt.plot(xs,ys)
plt.plot(xs,Ys)
ax = plt.gca()
ax.set_ylim(-2,1)
Out[2]:
(-2, 1)
In [3]:
# Use the `brentq` command to find the root.
x0 = brentq(lambda x:F(x)-x, -0.5,-0.4)
x0
Out[3]:
-0.4308350753693528
In [4]:
# Check i out
for i in range(3):
    x0 = f(x0)
    print(x0)
0.2125341096357123
-1.628002004250674
-0.4308350753693517

Looks good!