Fixed Point Iteration¶
Copyright (C) 2020 Andreas Kloeckner
MIT LicensePermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import numpy as np import matplotlib.pyplot as pt
Task: Find a root of the function below by fixed point iteration.
x = np.linspace(0, 4.5, 200) def f(x): return x**2 - x - 2 pt.plot(x, f(x)) pt.grid()
Actual roots: $2$ and $-1$. Here: focusing on $x=2$.
We can choose a wide variety of functions that have a fixed point at the root $x=2$:
(These are chosen knowing the root. But here we are only out to study the behavior of fixed point iteration, not the finding of fixed point functions--so that is OK.)
def fp1(x): return x**2-2 def fp2(x): return np.sqrt(x+2) def fp3(x): return 1+2/x def fp4(x): return (x**2+2)/(2*x-1) fixed_point_functions = [fp1, fp2, fp3, fp4]
for fp in fixed_point_functions: pt.plot(x, fp(x), label=fp.__name__) pt.ylim([0, 3]) pt.legend(loc="best")
<ipython-input-3-8e76f485a071>:3: RuntimeWarning: divide by zero encountered in true_divide def fp3(x): return 1+2/x
<matplotlib.legend.Legend at 0x7efd766b6df0>
for fp in fixed_point_functions: print(fp(2)) # All functions have 2 as a fixed point.
2 2.0 2.0 2.0
z = 2.1; fp = fp1 #z = 1; fp = fp2 #z = 1; fp = fp3 #z = 1; fp = fp4 n_iterations = 4 pt.figure(figsize=(8,8)) pt.plot(x, fp(x), label=fp.__name__) pt.plot(x, x, "--", label="$y=x$") pt.gca().set_aspect("equal") pt.xlim([0, 4]) pt.ylim([-0.5, 4]) pt.legend(loc="best") for i in range(n_iterations): z_new = fp(z) pt.arrow(z, z, 0, z_new-z) pt.arrow(z, z_new, z_new-z, 0) z = z_new print(z)
2.41 3.8081000000000005 12.501625610000003 154.29064289260796