Compute fixedpoint of f(x) = x^{0.5}
Contents
Compute fixedpoint of \(f(x) = x^{0.5}\)¶
Randall Romero Aguilar, PhD
This demo is based on the original Matlab demo accompanying the Computational Economics and Finance 2001 textbook by Mario Miranda and Paul Fackler.
Original (Matlab) CompEcon file: demslv03.m
Running this file requires the Python version of CompEcon. This can be installed with pip by running
!pip install compecon --upgrade
Last updated: 2022-Sept-04
About¶
Compute fixedpoint of \(f(x) = x^{0.5}\) using Newton, Broyden, and function iteration methods.
Initial values generated randomly. Some alrorithms may fail to converge, depending on the initial value.
True fixedpoint is \(x=1\).
import numpy as np
import pandas as pd
from compecon import tic, toc, NLP
Randomly generate starting point¶
xinit = np.random.rand(1) + 0.5
Set up the problem¶
def g(x):
return np.sqrt(x)
problem_as_fixpoint = NLP(g, xinit)
Equivalent Rootfinding Formulation¶
def f(x):
fval = x - np.sqrt(x)
fjac = 1-0.5 / np.sqrt(x)
return fval, fjac
problem_as_zero = NLP(f, xinit)
Compute fixed-point using Newton method¶
t0 = tic()
x1 = problem_as_zero.newton()
t1 = 100 * toc(t0)
n1 = problem_as_zero.fnorm
Compute fixed-point using Broyden method¶
t0 = tic()
x2 = problem_as_zero.broyden()
t2 = 100 * toc(t0)
n2 = problem_as_zero.fnorm
Compute fixed-point using function iteration¶
t0 = tic()
x3 = problem_as_fixpoint.fixpoint()
t3 = 100 * toc(t0)
n3 = np.linalg.norm(problem_as_fixpoint.fx - x3)
Print results¶
print('Hundredths of seconds required to compute fixed-point of g(x)=sqrt(x)')
print('using Newton, Broyden, and function iteration methods, starting at')
print('x = %4.2f\n' % xinit)
pd.DataFrame({
'Time': [t1, t2, t3],
'Norm of f': [n1, n2, n3],
'x': [x1, x2, x3]},
index=['Newton', 'Broyden', 'Function']
)
Hundredths of seconds required to compute fixed-point of g(x)=sqrt(x)
using Newton, Broyden, and function iteration methods, starting at
x = 0.87
Time | Norm of f | x | |
---|---|---|---|
Newton | 0.158477 | 5.427880e-12 | 1.0 |
Broyden | 0.563574 | 5.420553e-12 | 1.0 |
Function | 0.099730 | 4.122189e-09 | 1.0 |